package cn.fl.ass.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.multi.redis.service.IMultiRedisService;
import cmm.user.facade.system.dto.SysUsrDTO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.*;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.ass.controller.utils.ExportAssUtils;
import cn.fl.ass.service.*;
import cn.fl.ass.transform.AssDealCarCostVOTransform;
import cn.fl.ass.transform.AssTrailCarDVOTransform;
import cn.fl.ass.utils.ValidateUtil;
import cn.fl.ass.vo.*;
import cn.fl.capital.condition.CapFundVfDtlQueryCondition;
import cn.fl.capital.dto.CapFundVfDtlDTO;
import cn.fl.capital.service.ICapFundService;
import cn.fl.capital.service.ICapFundVfDtlApiService;
import cn.fl.capital.transform.CapFundVfDtlVOTransform;
import cn.fl.capital.vo.CapFundVO;
import cn.fl.capital.vo.CapFundVfDtlVO;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.finance.constant.FinLoanConstant;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.insurance.constant.InsuranceConstant;
import cn.fl.preloan.condition.PrjPrdDtlGpsQueryCondition;
import cn.fl.prjprddtlgps.service.IPrjPrdDtlGpsService;
import cn.fl.prjprddtlgps.vo.PrjPrdDtlGpsVO;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.project.constant.PrjPrdPaySchMConstant;
import cn.fl.project.dto.PrjPrdPaySchMDTO;
import cn.fl.project.service.*;
import cn.fl.project.vo.PrjBscInfoVO;
import cn.fl.project.vo.PrjPrdDtlVO;
import cn.fl.project.vo.PrjPrdLicInfoVO;
import cn.fl.project.vo.PrjPrdPaySchMVO;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysRegionService;
import cn.fl.system.service.ISysUlFilesRecService;
import cn.fl.system.service.ISysUsrService;
import cn.fl.system.vo.SysUsrVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lionbridge.activiti.util.redis.RedisLock;
import fl.ass.facade.condition.*;
import fl.ass.facade.constant.AssDealSellConstant;
import fl.ass.facade.constant.AssFileConstant;
import fl.ass.facade.constant.DealCarFlowEnum;
import fl.ass.facade.constant.InterfaceConstants;
import fl.ass.facade.dto.AssDealCarCostDTO;
import fl.ass.facade.dto.AssDealCarDTO;
import fl.ass.facade.dto.AssTrailCarDDTO;
import fl.flow.facade.flow.api.IFlowQueryApiService;
import fl.flow.facade.flow.condition.SysFlowSHQueryCondition;
import fl.flow.facade.flow.constant.FlowConstant;
import fl.flow.facade.flow.dto.SysFlowSHDTO;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @Description: 拖车信息明细表 控制层
 */
@Controller
@RequestMapping("/ass/assTrailCarD")
public class AssTrailCarDController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(AssTrailCarDController.class);

	/**
	 * AssTrailCarD 服务层BEAN
	 */
	@Autowired
	private IAssTrailCarDService assTrailCarDService;
	
	/**
	 * AssTrailCarM 服务层BEAN
	 */
	@Autowired
	private IAssTrailCarMService assTrailCarMService;
	
	/**
	 * 附件服务
	 */
	@Autowired
	private ISysUlFilesRecService sysUlFilesRecService;
	
	/**
	 * 处置服务
	 */
	@Autowired
	private IAssDealSellService assDealSellService;
	
	/**
	 * 赎回服务
	 */
	@Autowired
	private IAssDealRedeemService assDealRedeemService;
	
	/**
	 * 转优车服务
	 */
	@Autowired
	private IAssDealCarService assDealCarService;
	/**
	 * 拖车实际明细服务
	 */
	@Autowired
	private IAssTrailCarDInfService assTrailCarDInfService;
	/**
	 * 处置收款服务
	 */
	@Autowired
	private IAssDealRecAmtService assDealRecAmtService;
	/**
	 * 处置-转优车费用信息服务
	 */
	@Autowired
	private IAssDealCarCostService assDealCarCostService;
	/**
	 * 数据字典服务
	 */
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	
	/**
	 *ISysUsrService 服务层BEAN
	 */
	@Autowired
	private ISysUsrService sysUsrService;
	/**
	 *拖车交接单 服务层BEAN
	 */
	@Autowired
	private IAssTrailCarHvService assTrailCarHvService;
	/**
	 *客户资金核销记录 服务层BEAN
	 */
	@Autowired
	private  ICapFundVfDtlApiService  capFundVfDtlApiService;
    /**
     * SysRegion 服务层BEAN
     */
    @Autowired
    private ISysRegionService sysRegionService;
    @Autowired
	private IAssTrailCarFlowInsMcrLngService assTrailCarFlowInsMcrLngService;

    /**
     * 转优车文件记录服务
     */
    @Autowired
    private IAssFileLogService assFileLogService;

	/**
	 * 客户
	 */
	@Autowired
	private ICstBscInfoService cstBscInfoService;

	/**
	 * PrjPrdPaySchM 服务层BEAN
	 */
	@Autowired
	private IPrjPrdPaySchMService prjPrdPaySchMService;

	/**
	 * 项目基础服务
	 */
	@Autowired
	private IPrjBscInfoService prjBscInfoService;

	@Autowired
	private ICapFundService capFundService;

	@Autowired
	private IPrjPrdPaySchMApiService prjPrdPaySchMApiService;

	/**
	 * PrjPrdPaySchM 服务层BEAN
	 */
	@Autowired
	private IPrjPrdDtlService prjPrdDtlService;

    @Autowired
    private IPrjPrdDtlGpsService prjPrdDtlGpsService;

    @Autowired
    private IPrjPrdLicInfoService prjPrdLicInfoService;

    @Autowired
    private IPrjPrdVehInfoService prjPrdVehInfoService;

    /**
     * 缓存集群服务
     */
    @Resource(name = "userRedisService")
    private IMultiRedisService userRedisService;

	@Autowired
	private IFlowQueryApiService flowQueryApiService;

	/**
	 * 到拖车申请列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("ass/assTrailCarD/assTrailCarDInfoList");
		String grpCd = InterfaceConstants.BACK_STATUS_CD;//拖车状态
		String sysCd = CurrentThreadContext.getCurrentSysCd(); 
		String orgCd = CurrentThreadContext.getCurrentOrgCd();
		//获取拖车状态
		List<KeyValueVO> backStsList = this.assTrailCarMService.getKvList(grpCd, sysCd, orgCd);
		view.addObject("backStsList", backStsList);
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("ass/assTrailCarD/modify");
		view.addObject("id", id);
		return view;
	}
	
	/**
	 * 到拖车申请页面
	 */
	@RequestMapping(value = "/toApplyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toApplyPage(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		//获取页面参数：支付表ID和支付表号
		String paySchId = request.getParameter("paySchId");
		String paySchNo = request.getParameter("paySchNo");
		String prjPrdDtlId = request.getParameter("prjPrdDtlId");
		String prjId = request.getParameter("prjId");
		String businessType = request.getParameter("businessType");
		String prjTypCd = request.getParameter("prjTypCd");
		String prjNm = request.getParameter("prjNm");
		String orgName = request.getParameter("orgName");
		String cstId = request.getParameter("cstId");
		String cstNm = request.getParameter("cstNm");
        ModelAndView view = new ModelAndView("ass/assTrailCarD/assTrailCarDApply");
        try{
            if (StringUtils.isNotEmpty(prjId)) {
                boolean check = this.assTrailCarDService.checkCarIsChanging(Long.valueOf(prjId), Long.valueOf(prjPrdDtlId));
                if (check) {
                    throw new BaseException("车辆换车中，不允许发起该流程");
                }
                // 先判断是不是资管业务
                PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(Long.valueOf(prjId));
                if (PrjBscInfoConstant.PRJ_TYP_CD_CDDYWYQ.equals(prjBscInfoVO.getPrjTypCd())) {
                    throw new BaseException("车抵贷业务(YQ)不支持发起拖车");
                }
                Integer isInsBiz = prjBscInfoVO.getIsInsBiz();
                if (BaseConstant.IS_YESNO_NO == isInsBiz) {
                    // 非资管业务
                    List<PrjPrdPaySchMDTO> paySchMDTOS = this.prjPrdPaySchMApiService.selectEnabledListByPaySchId(Long.valueOf(paySchId));
                    if (CollectionUtils.isNotEmpty(paySchMDTOS)) {
                        PrjPrdPaySchMDTO dto = paySchMDTOS.get(0);
                        String enabledPaySchId = String.valueOf(dto.getId());
                        String enabledPaySchNo = dto.getPaySchNo();
                        view.addObject("enabledPaySchId", enabledPaySchId);
                        view.addObject("enabledPaySchNo", enabledPaySchNo);
                    }
                } else if (BaseConstant.IS_YESNO_YES == isInsBiz) {
                    // 资管业务：启用支付表是我司支付表
                    view.addObject("enabledPaySchId", paySchId);
                    view.addObject("enabledPaySchNo", paySchNo);
                }
            }
            // 我司支付表
            view.addObject("paySchId", paySchId);
            view.addObject("paySchNo", paySchNo);
            view.addObject("prjPrdDtlId", prjPrdDtlId);//项目产品明细表ID
            view.addObject("prjId", prjId);
            view.addObject("businessType", businessType);
            view.addObject("prjTypCd", prjTypCd);//项目类型
            view.addObject("prjNm", prjNm);
            view.addObject("orgName", orgName);//事业部名称
            view.addObject("cstId", cstId);
            view.addObject("cstNm", cstNm);//客户名称
            view.addObject("sysDate", DateUtils.formatDateToString(new Date(), DateUtils.YYYY_MM_DD));
            view.addObject("applyNm", CurrentThreadContext.getCurrentUserName());

			//获取拖车申请主表ID
			//Long pkId = this.assTrailCarDService.getPkId("ASS_TRAIL_CAR_M");
			//view.addObject("tcMasterId", pkId);

            //2018 09 13 add by zk 修改拖车渠道
            //获取下拉渠道备案省
            List<KeyValueVO> provinceKVList = this.sysRegionService.searchProvinceKVList();
            KeyValueVO keyValueVO = new KeyValueVO();
            keyValueVO.setKey("ALL");
            keyValueVO.setValue("总部");
            provinceKVList.add(0, keyValueVO);
            view.addObject("provinceKVList", provinceKVList);

            List<KeyValueVO> expressNm = this.sysDictionaryApiService.getKvList(InterfaceConstants.EXPRESS_NM, InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE);
            List<KeyValueVO> rcvRelationship = this.sysDictionaryApiService.getKvList(InterfaceConstants.RCV_RELATIONSHIP, InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE);
            List<KeyValueVO> backWayCd = this.sysDictionaryApiService.getKvList(InterfaceConstants.BACK_WAY_CD, InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE);
            view.addObject("expressNm", expressNm);
            view.addObject("rcvRelationship", rcvRelationship);
            view.addObject("backWayCd", backWayCd);
        }catch (BaseException ex) {
            BaseLogUtils.newLogger("到拖车页面失败").setThrowable(ex).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		}catch (Exception ex) {
            BaseLogUtils.newLogger("到拖车页面失败").setThrowable(ex).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		}
		return view;
	}

	/**
	 * 初始化拖车申请列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
	    try {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		AssTrailCarDQueryCondition qc = this.initTrailApplyParam(request, response);
		qc.setUsrId(CurrentThreadContext.getCurrentUserId());
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		page.setCondition(qc);

		//查询拖车申请列表
		Pager pager = this.assTrailCarDService.searchListPage(page);
		List<AssTrailCarDDTO> list = (List<AssTrailCarDDTO>) pager.getResultList();
		List<AssTrailCarDVO> listVo = AssTrailCarDVOTransform.toVOList(list);
		//查询对应的拖车审批流程信息
		if(CollectionUtils.isNotEmpty(listVo) && listVo.size()>0){
			List<SysFlowSHDTO> flowList = new ArrayList<SysFlowSHDTO>();
			SysFlowSHQueryCondition condition = new SysFlowSHQueryCondition();
			condition.setWordsInTheTable(InterfaceConstants.ASS_FLOW_S_H_ASS);
			condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
                List<Long> dataIdList = new ArrayList<>(listVo.size());
			//遍历拖车管理列表
			for(AssTrailCarDVO vo : listVo){
				if (StringUtils.isNotEmpty(vo.getMasterId())) {//拖车主表ID
                        dataIdList.add(vo.getMasterId());
                    } else {
                        // 根据已有的拖车明细查找主键
                        List<PrjPrdPaySchMDTO> enablePaySchList = this.prjPrdPaySchMApiService.selectEnabledListByPaySchId(vo.getPaySchId());
                        if (CollectionUtils.isNotEmpty(enablePaySchList)) {
                            Long enablePaySchId = enablePaySchList.get(0).getId();
                            AssTrailCarDQueryCondition assTrailCarDQueryCondition = new AssTrailCarDQueryCondition();
                            assTrailCarDQueryCondition.setPaySchId(enablePaySchId);
                            assTrailCarDQueryCondition.setIsDel(BaseConstant.IS_YESNO_NO);
                            assTrailCarDQueryCondition.setIsHis(BaseConstant.IS_YESNO_NO);
                            List<AssTrailCarDVO> assTrailCarDVOS = this.assTrailCarDService.searchDetailList(assTrailCarDQueryCondition);
                            if (CollectionUtils.isNotEmpty(assTrailCarDVOS)) {
                                dataIdList.add(assTrailCarDVOS.get(0).getMasterId());
                                vo.setMasterId(assTrailCarDVOS.get(0).getMasterId());
                            }
                        }
                    }
                }
                condition.setDataIdList(dataIdList);
                StopWatch sw = new StopWatch();
                sw.start();
                flowList = this.assTrailCarMService.searchFlowListPage(condition);
                sw.stop();
                BaseLogUtils.newLogger("查询多个流程历史耗时：" + sw.prettyPrint()).info();
                for (AssTrailCarDVO vo : listVo) {
					if(CollectionUtils.isNotEmpty(flowList) && flowList.size()>0){
						//遍历拖车审批流程列表
						for(SysFlowSHDTO dto : flowList){
                            if (dto.getDataId().equals(vo.getMasterId())) {
								vo.setPInstId(dto.getPInstId());//流程实例ID
								vo.setAudStsCd(dto.getAudStsCd());//流程审核状态
								vo.setpNo(dto.getPNo());//流程编号
							}
						}
					}
				}
			}
		ListPageVO<AssTrailCarDVO> listPage = new ListPageVO<AssTrailCarDVO>(listVo, pager.getTotalCount());
		return listPage;
        } catch (BaseException e) {
	        BaseLogUtils.newLogger("初始化拖车申请列表失败").setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
	        throw e;
        } catch (Exception e) {
            BaseLogUtils.newLogger("初始化拖车申请列表失败").setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        }
	}
	
	/**
	 * 初始化拖车申请列表-获取查询参数
	 */
	public AssTrailCarDQueryCondition initTrailApplyParam(HttpServletRequest request, HttpServletResponse response) {
		//获取页面参数
		String cstNm = request.getParameter("cstNm");
		String contNo = request.getParameter("contNo");
		String paySchNo = request.getParameter("paySchNo");
		String minDay = request.getParameter("minOverdueDay");
		String maxDay = request.getParameter("maxOverdueDay");
		String backStsCd = request.getParameter("backStsCd");

		AssTrailCarDQueryCondition qc = new AssTrailCarDQueryCondition();
		if (StringUtils.isNotEmpty(cstNm)) {//客户名称
			qc.setCstNm(cstNm);
		}
		if (StringUtils.isNotEmpty(contNo)) {//合同号
			qc.setContNo(contNo);
		}
		if (StringUtils.isNotEmpty(paySchNo)) {//支付表号
			qc.setPaySchNo(paySchNo);
		}
		if (StringUtils.isNotEmpty(minDay)) {//逾期天数-最小值
			Long minOverdueDay = Long.parseLong(minDay);
			qc.setMinOverdueDay(minOverdueDay);
		}
		if (StringUtils.isNotEmpty(maxDay)) {//逾期天数-最大值
			Long maxOverdueDay = Long.parseLong(maxDay);
			qc.setMaxOverdueDay(maxOverdueDay);
		}
		if (StringUtils.isNotEmpty(backStsCd)) {//拖车状态
			qc.setBackStsCd(backStsCd);
		}
		return qc;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.assTrailCarDService.removeById(Long.valueOf(id));
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			throw ex;
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			throw ex;
		}

		return result;
	}

	
	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		
		try {
			AssTrailCarDVO vo = this.assTrailCarDService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
			}
			result.setData(vo);
		}catch(BaseException ex) {
			BaseLogUtils.newLogger("获取拖车明细表数据失败").setKeys("id:" + id).setThrowable(ex).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
			throw ex;
		}catch(Exception ex) {
            BaseLogUtils.newLogger("获取拖车明细表数据失败").setKeys("id:" + id).setThrowable(ex).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		}
		return result;
	}

	/**
	 * 新增拖车信息明细信息
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		//获取页面参数
		String paySchId = request.getParameter("paySchId");
		String tcMasterId = request.getParameter("tcMasterId");
		String isOnline = request.getParameter("isOnline");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		AssTrailCarDVO entity = null;
		List<Long> ids = new ArrayList<Long>();
		if(StringUtils.isEmpty(paySchId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}else{
			ids.add(Long.valueOf(paySchId));
		}
		try {
			entity = new AssTrailCarDVO();
			//根据支付表ID获取拖车基本信息
			List<AssTrailCarDVO> vo = this.assTrailCarDService.selectByPaySchId(ids);
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
			}else{
				if(null != vo.get(0)){
					entity = vo.get(0);
				}
			}
			//拖车信息主表主键
			if(StringUtils.isEmpty(tcMasterId)){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
				return result;
			}else{
				entity.setMasterId(Long.valueOf(tcMasterId));
			}
			//获取GPS在线状态
			if(StringUtils.isNotEmpty(isOnline)){
				entity.setIsOnline(Integer.parseInt(isOnline));
			}
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setCrtTm(new Date());
			entity.setIsDel(BaseConstant.IS_YESNO_NO);
			//新增拖车明细数据
			Long id = this.assTrailCarDService.add(entity);
			result.setData(id);
		}catch (BaseException ex) {
			BaseLogUtils.newLogger("新增拖车明细数据失败").setThrowable(ex).setKeys("entity:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
			throw ex;
		}catch (Exception ex) {
            BaseLogUtils.newLogger("新增拖车明细数据失败").setThrowable(ex).setKeys("entity:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		}

		return result;
	}

	/**
	 * 修改拖车明细表信息
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String tcDetailId = request.getParameter("tcDetailId");
		String isOnline = request.getParameter("isOnline");//GPS在线状态
		String flag = request.getParameter("flag");//流程标识
		String backedFlagCd = request.getParameter("backedFlagCd");//拖回标记
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(tcDetailId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		AssTrailCarDVO entity = null;
		try {
			entity = new AssTrailCarDVO();
			entity.setId(Long.valueOf(tcDetailId));
			//判断是发起人,还是标记拖车状态的人
			if(StringUtils.isNotEmpty(flag)){
				if("12".equals(flag) ||"8".equals(flag) ){//修改拖车状态
					entity.setBackedFlagCd(backedFlagCd);
				}else if("2".equals(flag)){//修改GPS在线状态
					//获取GPS在线状态
					if(StringUtils.isNotEmpty(isOnline)){
						entity.setIsOnline(Integer.parseInt(isOnline));
					}
				}
			}
			//设置主表实体属性
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setMdfTm(new Date());
			boolean success = this.assTrailCarDService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
			}
		}catch (BaseException ex) {
			BaseLogUtils.newLogger("修改拖车明细失败").setKeys("tcDetailId:" + tcDetailId, "DATA:" + JSONObject.toJSONString(entity)).setThrowable(ex).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
			throw ex;
		}catch (Exception ex) {
            BaseLogUtils.newLogger("修改拖车明细失败").setKeys("tcDetailId:" + tcDetailId, "DATA:" + JSONObject.toJSONString(entity)).setThrowable(ex).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		}
		return result;
	}
	
	/**
	 * 获取拖车申请信息-JL
	 */
	@RequestMapping(value = "/getTrailCarApplyInfo.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getTrailCarApplyInfo(HttpServletRequest request, HttpServletResponse response) {
		// 用启用支付表查询逾期信息等
		String paySchId = request.getParameter("enabledPaySchId");
		String dataFlag = request.getParameter("dataFlag");
		List<Long> ids = new ArrayList<Long>();
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(paySchId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}else{
			ids.add(Long.valueOf(paySchId));
		}
		if(StringUtils.isEmpty(dataFlag)){
			dataFlag = "1";
		}//返回数据类型：1 ListPageVO, 2 List<AssTrailCarDVO>.
		try {
			List<AssTrailCarDVO> vo = this.assTrailCarDService.selectByPaySchId(ids);
			if(CollectionUtils.isEmpty(vo)){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
			}else{
				//转成listPage-用于显示页面设备信息
				ListPageVO<AssTrailCarDVO> listPage = new ListPageVO<AssTrailCarDVO>(vo, vo.size());
				if(null != vo.get(0)){
					//vo.get(0).setVoData(listPage);
				}
				//返回页面数据
				if("1".equals(dataFlag)){
					result.setData(listPage);
				}else{
					result.setData(vo);
				}
			}
		}catch(BaseException ex) {
			BaseLogUtils.newLogger("获取拖车申请信息失败").setKeys("paySchId:" + paySchId).setThrowable(ex).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
			throw ex;
		}catch(Exception ex) {
            BaseLogUtils.newLogger("获取拖车申请信息失败").setKeys("paySchId:" + paySchId).setThrowable(ex).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		}
		return result;
	}
	
	/**
	 * 保存附件信息
	 */
	@RequestMapping(value = "/uploadAttchment.do", method = { RequestMethod.POST,RequestMethod.GET })
	@ResponseBody
	public Object uploadAttchment(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String attchmnt = request.getParameter("docArray");
		String id = request.getParameter("pkId");
		String flag = request.getParameter("flag");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_FILE_UPLOAD_SUCC);
		if(StringUtils.isNotEmpty(attchmnt) && StringUtils.isNotEmpty(id)){
			//上传解析
			try{
				String fileRem = ""; //文件说明
				String cfgDtlCd = ""; //配置子编号
				String tabNm = ""; //数据表名
				String cfgCd = AssFileConstant.ASS_TRAIL_CAR_CFGCD; //配置编号：ASS001
				String cfgOrgCd = AssFileConstant.ASS_TRAIL_CAR_CFGORG; //组织架构代码：0000
				//判断标识确定文件配置编码
				if (StringUtils.isNotEmpty(flag)) {
					if("tcsq".equals(flag)){//拖车申请
						fileRem = "拖车申请";
						tabNm = AssFileConstant.ASS_TRAIL_CAR_TABNM; //拖车主表
						cfgDtlCd = AssFileConstant.ASS_TRAIL_CAR_CFGDTLCD_20;
					}else if("rkd".equals(flag)){//入库单
						fileRem = "入库单";
						tabNm = AssFileConstant.ASS_TRAIL_CAR_D_TABNM; //拖车明细表
						cfgDtlCd = AssFileConstant.ASS_TRAIL_CAR_CFGDTLCD_30;
					}else if("ckd".equals(flag)){//出库单
						fileRem = "出库单";
						tabNm = AssFileConstant.ASS_TRAIL_CAR_D_TABNM; //拖车明细表
						cfgDtlCd = AssFileConstant.ASS_TRAIL_CAR_CFGDTLCD_40;
					}else if("jjd".equals(flag)){//交接单
						fileRem = "交接单";
						tabNm = AssFileConstant.ASS_TRAIL_CAR_D_TABNM; //拖车明细表
						cfgDtlCd = AssFileConstant.ASS_TRAIL_CAR_CFGDTLCD_50;
					}else if("tccz".equals(flag)){//处置申请
						fileRem = "处置申请";
						tabNm = AssFileConstant.ASS_DEAL_SELL_TABNM; //处置主表
						cfgDtlCd = AssFileConstant.ASS_TRAIL_CAR_CFGDTLCD_60;
					}else if("cztcr".equals(flag)){//处置-提车人
						fileRem = "处置提车人附件";
						tabNm = AssFileConstant.ASS_DEAL_SELL_TABNM; //处置主表
						cfgDtlCd = AssFileConstant.ASS_TRAIL_CAR_CFGDTLCD_70;
					}else if("tcsh".equals(flag)){//赎回申请
						fileRem = "赎回申请";
						tabNm = AssFileConstant.ASS_DEAL_REDEEM_TABNM; //赎回主表
						cfgDtlCd = AssFileConstant.ASS_TRAIL_CAR_CFGDTLCD_80;
					}else if ("tcsh_gps".equals(flag)) {
					    // 拖车赎回gps上传附件
                        fileRem = "赎回申请GPS附件";
                        tabNm = AssFileConstant.ASS_DEAL_REDEEM_TABNM; //赎回主表
                        cfgDtlCd = AssFileConstant.ASS_TRAIL_CAR_CFGDTLCD_120;
                    }else if("shtcr".equals(flag)){//赎回-提车人
						fileRem = "赎回提车人附件";
						tabNm = AssFileConstant.ASS_DEAL_REDEEM_TABNM; //赎回主表
						cfgDtlCd = AssFileConstant.ASS_TRAIL_CAR_CFGDTLCD_90;
					}else if("zycsq".equals(flag)){//转优车申请
						fileRem = "转优车申请";
						tabNm = AssFileConstant.ASS_DEAL_CAR_TABNM; //转优车主表
						cfgDtlCd = AssFileConstant.ASS_TRAIL_CAR_CFGDTLCD_100;
					}else if("lkpz_tc".equals(flag)){//来款凭证:拖车申请流程
						fileRem = "来款凭证（拖车申请流程）";
						tabNm = AssFileConstant.ASS_TRAIL_CAR_TABNM; //拖车主表
						cfgDtlCd = AssFileConstant.ASS_TRAIL_CAR_CFGDTLCD_110;
					}else if("lkpz_sh".equals(flag)){//来款凭证:赎回流程
						fileRem = "来款凭证（赎回流程）";
						tabNm = AssFileConstant.ASS_DEAL_REDEEM_TABNM; //拖车主表
						cfgDtlCd = AssFileConstant.ASS_TRAIL_CAR_CFGDTLCD_110;
					}else if("lkpz_cz".equals(flag)){//来款凭证:处置流程
						fileRem = "来款凭证（处置流程）";
						tabNm = AssFileConstant.ASS_DEAL_SELL_TABNM; //处置主表
						cfgDtlCd = AssFileConstant.ASS_TRAIL_CAR_CFGDTLCD_110;
					}else if("tcsq_hj".equals(flag)){
					    // 拖车申请（函件）
                        fileRem = "拖车申请（函件）";
                        tabNm = AssFileConstant.ASS_TRAIL_CAR_TABNM;
                        cfgCd = AssFileConstant.ASS_HANJIAN_FILE_CFG_CD;
                        cfgDtlCd = AssFileConstant.ASS_HANJIAN_CFGDTLCD_1;
                    }else{
						result.setSuccess(BaseConstant.IS_YESNO_NO);
						result.setInfo("文件上传标识不能识别！不能上传附件!");
						return result;
					}
				}else{
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("文件上传标识为空！不能上传附件!");
					return result;
				}
				Boolean attchmntPass = this.sysUlFilesRecService.addAttchmnt(String.valueOf(id), attchmnt, cfgCd, cfgDtlCd, tabNm, fileRem, null, null, false, cfgOrgCd);
				if(null == attchmntPass || attchmntPass == false){
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("拖车模块附件上传失败!");
					BaseLogUtils.newLogger("拖车模块附件上传失败").setBussinessId(id).info();
				}
				result.setData(id);//设置附件关联主键
			}catch (BaseException ex) {
                BaseLogUtils.newLogger("拖车模块附件上传失败").setThrowable(ex).setKeys("id:" + id).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
                throw ex;
			}catch (Exception ex) {
                BaseLogUtils.newLogger("拖车模块附件上传失败").setThrowable(ex).setKeys("id:" + id).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
                throw ex;
			}
		}
		return result;
	}
	
	/**
	 * 新增处置信息主表数据
	 * 同时发起处置申请流程
	 */
	@RequestMapping(value = "/addDealInfo.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object addDealInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		//获取页面参数
		String masterId = request.getParameter("tcMasterId");
		String detailId = request.getParameter("tcDetailId");
		// 获取预选保存的处置id
        String sellId = request.getParameter("sellId");
		String infoId = request.getParameter("infoId");
		String cstId = request.getParameter("cstId");
		String cstNm = request.getParameter("cstNm");
		String buyerTypeCd = request.getParameter("buyerTypeCd");
		String sellAmt = request.getParameter("sellAmt");
		String sellChannelCd = request.getParameter("sellChannelCd");
		String dataTypeCd = request.getParameter("dataTypeCd");
		String sellDesc = request.getParameter("sellDesc");
		String buOrgCd = request.getParameter("buOrgCd");
		String buyerNm = request.getParameter("buyerNm");
		String buyerCd = request.getParameter("buyerCd");
		String buyerTel = request.getParameter("buyerTel");
		String buyerCompanyNm = request.getParameter("buyerCompanyNm");
		String buyerCompanyContact = request.getParameter("buyerCompanyContact");
		String buyerCompanyTel = request.getParameter("buyerCompanyTel");
		String buyerCompanyCode = request.getParameter("buyerCompanyCode");
		String prjPrdDtlId = request.getParameter("prjPrdDtlId");
		String prjId = request.getParameter("prjId");
		String businessType = request.getParameter("businessType");
		String prjTypCd = request.getParameter("prjTypCd");
		String prjNm = request.getParameter("prjNm");
		String orgName = request.getParameter("orgName");
		String sellEstiAmt = request.getParameter("sellEstiAmt");//处置评估价
		String sellEstiDt = request.getParameter("stDt");//处置评估时间
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		AssDealSellVO entity = new AssDealSellVO();
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("orgCode",buOrgCd);//事业部简称-流程使用
		//map.put("orgCode","ZK");//事业部简称-流程使用
		try {
			//设置主表实体属性
			if(StringUtils.isNotEmpty(masterId)){
				entity.setMasterId(Long.parseLong(masterId));
			}
			if(StringUtils.isNotEmpty(detailId)){
				entity.setDetailId(Long.parseLong(detailId));
            }
            if(StringUtils.isNotEmpty(sellId)){
                entity.setId(Long.parseLong(sellId));
            }
			if(StringUtils.isNotEmpty(infoId) && StringUtils.isNotEmpty(dataTypeCd)){
				if(!"null".equals(infoId) && "1".equals(dataTypeCd)){//重卡事业部
					entity.setDataId(Long.parseLong(infoId));
				}
			}
			if(StringUtils.isNotEmpty(cstId)){
				entity.setCstId(Long.parseLong(cstId));
			}
			if(StringUtils.isNotEmpty(sellAmt)){//元转分
				entity.setSellAmt(DecimalUtils.convertYuanToFen(Double.valueOf(sellAmt)));
			}
			entity.setCstNm(cstNm);
			entity.setBuyerTypeCd(buyerTypeCd);
			entity.setSellChannelCd(sellChannelCd);
			entity.setDataTypeCd(dataTypeCd);
			entity.setSellDesc(sellDesc);
			entity.setBuyerNm(buyerNm);
			entity.setBuyerCd(buyerCd);
			entity.setBuyerTel(buyerTel);
			entity.setBuyerCompanyNm(buyerCompanyNm);
			entity.setBuyerCompanyContact(buyerCompanyContact);
			entity.setBuyerCompanyTel(buyerCompanyTel);
			entity.setBuyerCompanyCode(buyerCompanyCode);
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setCrtTm(new Date());
			entity.setIsDel(BaseConstant.IS_YESNO_NO);
			entity.setApplyNm(CurrentThreadContext.getCurrentUserName());//申请人
			if(StringUtils.isNotEmpty(sellEstiAmt)){
				entity.setSellEstiAmt(Long.valueOf(sellEstiAmt));//处置评估价
			}
			if(StringUtils.isNotEmpty(sellEstiDt)){
				entity.setSellEstiDt(DateUtils.formatStringToDate(sellEstiDt, DateUtils.YYYY_MM_DD));//处置评估时间
			}
			//保存处置信息
            boolean success = this.assDealSellService.modify(entity);
            if(success){
				//设置流程参数
				AssTrailCarDQueryCondition qc = new AssTrailCarDQueryCondition();
				qc.setId(Long.valueOf(sellId));//处置主表ID
				qc.setOrgName(orgName);//项目所属事业部名称
				qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
				qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
				qc.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());//当前登录人事业部代码
				qc.setUsrId(CurrentThreadContext.getCurrentUserId());
				qc.setUsrNm(CurrentThreadContext.getCurrentUserName());
				if("ZC".equals(map.get("orgCode"))){
					qc.setFlowModelType(FlowConstant.FLOW_MODEL_TYP_ZC_DEAL);//"042"专车拖车管理处置
	        	}else {
					qc.setFlowModelType(FlowConstant.FLOW_MODEL_TYP_ASS_DEAL);//"016"拖车管理处置
				}				qc.setFlow_Map(map);//附加参数
				if(StringUtils.isNotEmpty(prjPrdDtlId)){//项目产品明细表ID
					qc.setPrjPrdDtlId(Long.parseLong(prjPrdDtlId));
				}
				if(StringUtils.isNotEmpty(prjId)){//项目基础信息表ID
					qc.setPrjId(Long.parseLong(prjId));
				}
				if(StringUtils.isNotEmpty(cstId)){//客户ID
					qc.setCstId(Long.parseLong(cstId));
				}
				qc.setBusinessType(businessType);
				qc.setPrjTypCd(prjTypCd);
				qc.setPrjNm(prjNm);
				qc.setCstNm(cstNm);
				//发起处置申请流程
				result = this.assTrailCarMService.addTrailCarApply(qc);
				//发起成功修改拖车明细表状态
				if(result.getSuccess()==1){
					AssTrailCarDVO dEntity = new AssTrailCarDVO();
					if(StringUtils.isEmpty(detailId)){
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
                        return result;
					}else{
						dEntity.setId(Long.parseLong(detailId));
						dEntity.setDealTypeCd("1");//处置方式：处置
						dEntity.setDealStsCd("1");//处置状态：处置中
						boolean succ = this.assTrailCarDService.modify(dEntity);
						if(!succ){
						    BaseLogUtils.newLogger("修改拖车明细表状态失败").setKeys("detailId:" + detailId, "DATA:" + JSONObject.toJSONString(dEntity)).info();
						}
                        AssDealCarDTO data = (AssDealCarDTO) result.getData();
                        AssTrailCarDVO assTrailCarDVO = assTrailCarDService.selectById(Long.valueOf(detailId));
                        ProductStatusLogVO productStatusLogVO = new ProductStatusLogVO();
                        productStatusLogVO.setPaySchId(assTrailCarDVO.getPaySchId());
                        productStatusLogVO.setPrjPrdId(Long.valueOf(prjPrdDtlId));
                        productStatusLogVO.setCurrentStatus(InterfaceConstants.PAY_STATUS_CD_S01060201);
                        productStatusLogVO.setOpCode(InterfaceConstants.OP_CODE_OP0024);
                        productStatusLogVO.setProcessInstanceId(data.getProcId());
                        productStatusLogVO.setProcessInstanceCode(data.getProcNo());
                        this.assTrailCarMService.updateYQPrdStsCdByFlow(productStatusLogVO);
					}
				}
				//设置处置主表ID
				result.setData(sellId);
			}else{
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("发起处置申请流程失败！");
			}
		}catch (BaseException ex) {
			BaseLogUtils.newLogger("新增处置信息主表数据失败").setThrowable(ex).setKeys("DATA:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
			throw ex;
		}catch (Exception ex) {
            BaseLogUtils.newLogger("新增处置信息主表数据失败").setThrowable(ex).setKeys("DATA:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		}
		return result;
	}
	
	/**
	 * 新增赎回信息主表数据
	 * 同时发起赎回申请流程
	 */
	@RequestMapping(value = "/addRedeemInfo.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object addRedeemInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		//获取页面参数
		String masterId = request.getParameter("tcMasterId");
		String detailId = request.getParameter("tcDetailId");
		// 获取提前生成的赎回id
        String redeemId = request.getParameter("redeemId");
		String cstId = request.getParameter("cstId");
		String cstNm = request.getParameter("cstNm");
		String redeemTypeCd = request.getParameter("redeemTypeCd");
		String redeemAddr = request.getParameter("redeemAddr");
		String redeemTm = request.getParameter("redeemTm");
		String isOnline = request.getParameter("isOnline");
		String overdueAmt = request.getParameter("overdueAmt");
		String interestAmt = request.getParameter("interestAmt");
		String redeemAmt = request.getParameter("redeemAmt");
		String redeemDesc = request.getParameter("redeemDesc");
		String buOrgCd = request.getParameter("buOrgCd");
		String prjPrdDtlId = request.getParameter("prjPrdDtlId");
		String prjId = request.getParameter("prjId");
		String businessType = request.getParameter("businessType");
		String prjTypCd = request.getParameter("prjTypCd");
		String prjNm = request.getParameter("prjNm");
		String orgName = request.getParameter("orgName");
		//汽车金融发起人：填写风险保证金1
		String depositPct = request.getParameter("depositPct");
		String amtTypeCd = request.getParameter("amtTypeCd");
		String depositAmt = request.getParameter("depositAmt");
		String depositBaseAmt = request.getParameter("depositBaseAmt");
        // 赎回支付表号
        String paySchId = request.getParameter("paySchId");
		// 结清赎回irr
		String cstStlIrr = request.getParameter("cstStlIrr");
		// 结清优惠金额1
        String discountAmt = request.getParameter("discountAmt");
        // 应收款金额
        String receivableAmt = request.getParameter("receivableAmt");
        // 赎回方
        String redeemWayCd = request.getParameter("redeemWayCd");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        if (StringUtils.isEmpty(paySchId)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            return result;
        }
        if (StringUtils.isNotEmpty(redeemTypeCd) || StringUtils.isNotEmpty(prjPrdDtlId)) {
            // 赎回结清校验YQ支付表
            result = this.assDealRedeemService.checkAssRedeemFlow4YQ(redeemTypeCd, Long.valueOf(prjPrdDtlId));
            if (BaseConstant.IS_YESNO_NO == result.getSuccess()) {
                return result;
            }
        }
		AssDealRedeemVO entity = new AssDealRedeemVO();
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("orgCode",buOrgCd);//事业部简称-流程使用
		//map.put("orgCode","ZK");//事业部简称-流程使用
		try {
			//设置主表实体属性
			if(StringUtils.isNotEmpty(masterId)){
				entity.setMasterId(Long.parseLong(masterId));
			}
			if(StringUtils.isNotEmpty(detailId)){
				entity.setDetailId(Long.parseLong(detailId));
			}
            if(StringUtils.isNotEmpty(redeemId)){
                entity.setId(Long.parseLong(redeemId));
            }
			if(StringUtils.isNotEmpty(cstId)){
				entity.setCstId(Long.parseLong(cstId));
			}
			if(StringUtils.isNotEmpty(redeemTm)){
				entity.setRedeemTm(DateUtils.formatStringToDate(redeemTm, DateUtils.YYYY_MM_DD));
			}
			if(StringUtils.isNotEmpty(isOnline)){
				entity.setIsOnline(Integer.parseInt(isOnline));
			}
            if(StringUtils.isNotEmpty(redeemWayCd)){
                entity.setRedeemWayCd(redeemWayCd);
            }
			//赎回结清-保存赎回逾期信息
			if("1".equals(redeemTypeCd)){
				if(StringUtils.isNotEmpty(overdueAmt)){//元转分
					entity.setOverdueAmt(DecimalUtils.convertYuanToFen(Double.valueOf(overdueAmt)));
				}
				if(StringUtils.isNotEmpty(interestAmt)){//元转分
					entity.setInterestAmt(DecimalUtils.convertYuanToFen(Double.valueOf(interestAmt)));
				}
				if(StringUtils.isNotEmpty(redeemAmt)){//元转分
					entity.setRedeemAmt(DecimalUtils.convertYuanToFen(Double.valueOf(redeemAmt)));
				}
				// 应收款金额
                if(StringUtils.isNotEmpty(receivableAmt)){
                    entity.setReceivableAmt(DecimalUtils.convertYuanToFen(Double.valueOf(receivableAmt)));
                }
			}
			if(StringUtils.isNotEmpty(depositPct)){//赎回保证金比例
				entity.setDepositPct(Double.parseDouble(depositPct));;
			}
			if(StringUtils.isNotEmpty(depositAmt)){//赎回保证金
				entity.setDepositAmt(DecimalUtils.convertYuanToFen(Double.valueOf(depositAmt)));
			}
			if(StringUtils.isNotEmpty(depositBaseAmt)){//赎回保证金基数
				entity.setDepositBaseAmt(DecimalUtils.convertYuanToFen(Double.valueOf(depositBaseAmt)));
			}
			entity.setAmtTypeCd(amtTypeCd);//赎回保证金计算基数类型
			entity.setCstNm(cstNm);
			entity.setRedeemTypeCd(redeemTypeCd);
			entity.setRedeemAddr(redeemAddr);
			entity.setRedeemDesc(redeemDesc);
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setCrtTm(new Date());
			entity.setIsDel(BaseConstant.IS_YESNO_NO);
			
			//保存处置信息
			Long id = this.assDealRedeemService.add(entity);
			if(null != id){
				//设置流程参数
				AssTrailCarDQueryCondition qc = new AssTrailCarDQueryCondition();
				qc.setId(Long.valueOf(redeemId));//赎回主表ID
				qc.setOrgName(orgName);//项目所属事业部名称
				qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
				qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
				qc.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());//当前登录人事业部代码
				qc.setUsrId(CurrentThreadContext.getCurrentUserId());
				qc.setUsrNm(CurrentThreadContext.getCurrentUserName());
				if("ZC".equals(map.get("orgCode"))){
					qc.setFlowModelType(FlowConstant.FLOW_MODEL_TYP_ZC_REDEEM);//"041"专车拖车赎回
	        	}else {
					qc.setFlowModelType(FlowConstant.FLOW_MODEL_TYP_ASS_REDEEM);//"018"拖车赎回
				}				qc.setFlow_Map(map);//附加参数
				if(StringUtils.isNotEmpty(prjPrdDtlId)){//项目产品明细表ID
					qc.setPrjPrdDtlId(Long.parseLong(prjPrdDtlId));
				}
				if(StringUtils.isNotEmpty(prjId)){//项目基础信息表ID
					qc.setPrjId(Long.parseLong(prjId));
				}
				if(StringUtils.isNotEmpty(cstId)){//客户ID
					qc.setCstId(Long.parseLong(cstId));
				}
				qc.setBusinessType(businessType);
				qc.setPrjTypCd(prjTypCd);
				qc.setPrjNm(prjNm);
				qc.setCstNm(cstNm);
				//发起赎回申请流程
				result = this.assTrailCarMService.addTrailCarApply(qc);
				//发起成功修改拖车明细表状态
				if(result.getSuccess()==1){
					AssTrailCarDVO dEntity = new AssTrailCarDVO();
					if(StringUtils.isEmpty(detailId)){
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
                        return result;
					}else {
                        dEntity.setId(Long.parseLong(detailId));
                        dEntity.setDealTypeCd("2");//处置方式：赎回
                        if ("1".equals(redeemTypeCd)) {//赎回方式：赎回结清
                            dEntity.setDealStsCd("4");//处置状态：赎回结清中
                        } else if ("2".equals(redeemTypeCd)) {//赎回方式：赎回转正常
                            dEntity.setDealStsCd("7");//处置状态：赎回转正常中
                        }
                        boolean succ = this.assTrailCarDService.modify(dEntity);
                        if (!succ) {
                            BaseLogUtils.newLogger("修改拖车明细表状态失败").setKeys("detailId:" + detailId, "DATA:" + JSONObject.toJSONString(dEntity)).info();
                        }
                        if (InterfaceConstants.REDEEM_TYPE_CD_1.equals(redeemTypeCd)) {
                            // 仅赎回结清保存IRR
                            boolean isSuccess = this.assDealRedeemService.saveStlCstIrrAndDiscountAmt(id, Long.valueOf(paySchId), Double.valueOf(cstStlIrr), Double.valueOf(DecimalUtils.convertYuanToFen(Double.valueOf(discountAmt))), CurrentThreadContext.getCurrentUserId());
                            if (isSuccess == false) {
                                result.setSuccess(BaseConstant.IS_YESNO_NO);
                                result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
                                return result;
                            }
                        }
                    }
				}
				//设置赎回主表ID
				result.setData(id);
			}else{
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("发起赎回申请流程失败！");
				BaseLogUtils.newLogger("新增赎回信息主表数据失败").setKeys("id:" + id, "DATA:" + JSONObject.toJSONString(entity)).info();
			}
		}catch (BaseException ex) {
			BaseLogUtils.newLogger("新增赎回信息主表数据失败").setThrowable(ex).setKeys("DATA:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
			throw ex;
		}catch (Exception ex) {
            BaseLogUtils.newLogger("新增赎回信息主表数据失败").setThrowable(ex).setKeys("DATA:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		}
		return result;
	}

    /**
     * 计算对客结清irr和结清优惠金额1
     */
    @RequestMapping(value = "/calcCstStlIrrAndDiscountAmt.do", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Object calcCstStlIrrAndDiscountAmt(HttpServletRequest request) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        // 支付表id
        String paySchId = request.getParameter("paySchId");
        // 资金列表的可用金额合计（当做结清金额计算irr）
        String totalAvailableAmt = request.getParameter("totalAvailableAmt");
        // 赎回结清id
        String redeemId = request.getParameter("redeemId");
        // 赎回结清金额
        String redeemAmt = request.getParameter("redeemAmt");
        // 计算irr标识(1:第一个财务节点;2:第二个财务节点)
        String calcType = request.getParameter("calcType");
        // 结清金额
        Long stlAmt = 0L;
        // 申请时间
        Date stlStDt = null;
        if ("1".equals(calcType)) {
            if (StringUtils.isEmpty(paySchId) || StringUtils.isEmpty(redeemAmt)) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("计算结清对客IRR时参数不完整！");
                return result;
            }
            stlAmt = Long.valueOf(redeemAmt);
            stlStDt = DateUtils.getCurrentDate(DateUtils.YYYY_MM_DD);
        }
        if ("2".equals(calcType)) {
        if (StringUtils.isEmpty(paySchId) || StringUtils.isEmpty(totalAvailableAmt) ||StringUtils.isEmpty(redeemId)) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("计算结清对客IRR时参数不完整！");
                return result;
            }
            stlAmt = Long.valueOf(totalAvailableAmt);
            AssDealRedeemVO assDealRedeemVO = this.assDealRedeemService.selectById(Long.valueOf(redeemId));
            stlStDt = assDealRedeemVO.getCrtTm();
        }
        try {
            if (null == stlStDt) {
                throw new BaseException("无法获得拖车赎回发起时间");
            }
            // 计算赎回结清IRR和结清优惠金额1
            Map<String, Double> calcStlCstIRRAndDiscount = this.assDealRedeemService.getCalcStlCstIRRAndDiscount(Long.valueOf(paySchId), stlAmt, stlStDt);
            JSONObject json = new JSONObject();
            if (CollectionUtils.isMapNotEmpty(calcStlCstIRRAndDiscount)) {
                Double cstStlIrr = calcStlCstIRRAndDiscount.get("irr");
                Double discountAmt = calcStlCstIRRAndDiscount.get("discountAmtIRR");
                if ("2".equals(calcType)) {
                    boolean success = this.assDealRedeemService.saveStlCstIrrAndDiscountAmt(Long.valueOf(redeemId), Long.valueOf(paySchId), cstStlIrr, discountAmt, CurrentThreadContext.getCurrentUserId());
                    if (false == success) {
                        throw new BaseException("保存对客结清IRR和结清优惠金额1异常！");
                    }
                }
                // 返回的irr是小数，结清优惠金额1金额是分
                json.put("cstStlIrr", cstStlIrr);
                json.put("discountAmt", discountAmt / 100);
            } else {
                json.put("cstStlIrr", 0);
                json.put("discountAmt", 0);
            }
            result.setData(json);
        } catch (BaseException e) {
            BaseLogUtils.newLogger("计算对客IRR和结清优惠金额1失败").setKeys("paySchId:" + paySchId, "redeemId:" + redeemId, "totalStlAmt:" + totalAvailableAmt).setThrowable(e).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        } catch (Exception e) {
            BaseLogUtils.newLogger("计算对客IRR和结清优惠金额1失败").setKeys("paySchId:" + paySchId, "redeemId:" + redeemId, "totalStlAmt:" + totalAvailableAmt).setThrowable(e).setWarning(false).error(LogExceptionEnum.API_CODE_0102);
            throw e;
        }
        return result;
    }
	
	/**
	 * 到出入库交接单页面
	 */
	@RequestMapping(value = "/toOutEntryPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toOutEntryPage(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		//获取拖车主表ID和明细表ID
		String tcMasterId = request.getParameter("tcMasterId");
		String detailId = request.getParameter("tcDetailId");
		ModelAndView view = new ModelAndView("ass/assTrailCarD/assEntryOrderEdit");
		view.addObject("tcMasterId", tcMasterId);
		view.addObject("detailId", detailId);
		return view;
	}

	/**
	 * 到处置流程附加信息页面
	 */
	@RequestMapping(value = "/toDealViewPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toDealViewPage(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		//获取页面标识和拖车主表ID
		String flag = request.getParameter("flag");//
		String deal_Id = request.getParameter("deal_Id");
		String processId= request.getParameter("processInstanceId");
		String taskDefKey= request.getParameter("taskDefKey");//节点id
		String taskNm= request.getParameter("taskNm");//节点名称
		String SZSH= request.getParameter("SZSH");//省总审核
		String sysCd = CurrentThreadContext.getCurrentSysCd(); 
		String orgCd = CurrentThreadContext.getCurrentOrgCd();
		String isDetail = request.getParameter("isDetail");
		ModelAndView view = new ModelAndView("ass/assTrailCarM/assDealApplyView");
		try {
			//处置接收人类型
			List<KeyValueVO> buyerTypeList = this.assTrailCarMService.getKvList(InterfaceConstants.BUYER_TYPE_CD, sysCd, orgCd);
			view.addObject("buyerTypeList", buyerTypeList);
			//处置路径
			List<KeyValueVO> sellChannelList = this.assTrailCarMService.getKvList(InterfaceConstants.SELL_CHANNEL_CD, sysCd, orgCd);
			view.addObject("sellChannelList", sellChannelList);
			//数据类型
			List<KeyValueVO> dataTypeList = this.assTrailCarMService.getKvList(InterfaceConstants.DATA_TYPE_CD_SY, sysCd, orgCd);
			//亏损原因
			List<KeyValueVO> lossCauseCdJosn= this.assTrailCarMService.getKvList(InterfaceConstants.LOSS_CAUSE_CD, sysCd, orgCd);
     
			//获取保底价格及经营贷——LNG——保险贷
			AssDealSellVO assDealSellVO = this.assDealSellService.selectById(Long.valueOf(deal_Id));
			if(null != assDealSellVO && null != assDealSellVO.getMasterId()){
				Long masterId = assDealSellVO.getMasterId();
				Long sellEstiAmt = assDealSellVO.getSellEstiAmt();
				Long baseAllAmt=assTrailCarFlowInsMcrLngService.getAllMoney(String.valueOf(masterId));
				view.addObject("baseAllAmt", baseAllAmt);
				if(StringUtils.isEmpty(sellEstiAmt)){
					view.addObject("sellEstiAmt", sellEstiAmt);
				}else{
					view.addObject("sellEstiAmt", (sellEstiAmt/100));
				}

				AssTrailCarDVO assTrailCarDVO = assTrailCarDService.selectById(assDealSellVO.getDetailId());
				view.addObject("paySchId", assTrailCarDVO.getPaySchId());
			}
			view.addObject("dataTypeList", dataTypeList);
			view.addObject("flag", flag);
			view.addObject("deal_Id", deal_Id);
			view.addObject("processId", processId);
			view.addObject("taskDefKey", taskDefKey);
			view.addObject("taskNm", taskNm);////节点名称
			view.addObject("sysDate", DateUtils.formatDateToString(new Date(), DateUtils.YYYY_MM_DD));
			view.addObject("loginUsrNm", CurrentThreadContext.getCurrentUserName());
			view.addObject("lossCauseCdJosn", JSON.toJSON(lossCauseCdJosn));//亏损原因
			//
			view.addObject("SZSH",SZSH);//亏损原因控制是否可以编辑
			view.addObject("isDetail", isDetail);

			//处置流程-查询绑定资金数据
			BaseLogUtils.newLogger("处置流程-查询绑定资金数据开始").setKeys("DATA:" + JSON.toJSONString(view)).info();
			AssTrailCarDVO assTrailCarDVO = assTrailCarDService.selectById(assDealSellVO.getDetailId());
			// 现在查出的是启用支付表
			String paySchId = String.valueOf(assTrailCarDVO.getPaySchId());
			if (StringUtils.isNotEmpty(paySchId)) {
                List<PrjPrdPaySchMDTO> prjPrdPaySchMDTOS = this.prjPrdPaySchMService.searchTheSamePrdOtherPaySchMList(Long.valueOf(paySchId));
                for (PrjPrdPaySchMDTO prjPrdPaySchMDTO : prjPrdPaySchMDTOS) {
                    if (PrjPrdPaySchMConstant.PAY_SCH_TYP_CD_WS.equals(prjPrdPaySchMDTO.getPaySchTypCd())) {
                        // 现在查出的-1支付表
                        String wsPaySchId = prjPrdPaySchMDTO.getId().toString();
                        view.addObject("wsPaySchId", wsPaySchId);
                    }
                }
            }
			view.addObject("paySchId", paySchId);
			view = findBindFundData(request, view, paySchId, deal_Id);
            BaseLogUtils.newLogger("处置流程-查询绑定资金数据结束").setKeys("DATA:" + JSON.toJSONString(view)).info();
		} catch (Exception e) {
		    BaseLogUtils.newLogger("跳转拖车处理流程附加信息页面异常").setThrowable(e).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
		    throw e;
		}
		
		String mdfSellCost = request.getParameter("mdfSellCost");//是否可以编辑处置变卖费用信息
		view.addObject("mdfSellCost", mdfSellCost);
		return view;
	}

	/**
	 * 到赎回流程附加信息页面
	 */
	@RequestMapping(value = "/toRedeemViewPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toRedeemViewPage(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		//获取页面标识和拖车主表ID
		String flag = request.getParameter("flag");
		String redeem_Id = request.getParameter("redeem_Id");
		String isDetail = request.getParameter("isDetail");
		String sysCd = CurrentThreadContext.getCurrentSysCd(); 
		String orgCd = CurrentThreadContext.getCurrentOrgCd();
		ModelAndView view = new ModelAndView("ass/assTrailCarM/assRedeemApplyView");
		//赎回方式
		List<KeyValueVO> redeemTypeList = this.assTrailCarMService.getKvList(InterfaceConstants.REDEEM_TYPE_CD, sysCd, orgCd);
		view.addObject("redeemTypeList", redeemTypeList);
		//赎回保证金计算基数类型
        List<SysDictionaryDTO> amtTypeCdList = sysDictionaryApiService.searchGroup(sysCd, orgCd, InterfaceConstants.AMT_TYPE_CD);
        view.addObject("amtTypeCdList", amtTypeCdList);
		view.addObject("flag", flag);
		view.addObject("redeem_Id", redeem_Id);
		view.addObject("sysDate", DateUtils.formatDateToString(new Date(), DateUtils.YYYY_MM_DD));
		view.addObject("loginUsrNm", CurrentThreadContext.getCurrentUserName());
        //赎回方式
        List<KeyValueVO> redeemWayList = this.assTrailCarMService.getKvList(InterfaceConstants.REDEEM_WAY_CD, sysCd, orgCd);
        view.addObject("redeemWayList", redeemWayList);
		//根据id查询主表
		AssDealRedeemVO assDealRedeemVO = assDealRedeemService.selectById(Long.valueOf(redeem_Id));

		//查询拖车明细信息
		AssTrailCarDVO assTrailCarDVO = assTrailCarDService.selectById(assDealRedeemVO.getDetailId());
		// 获取GPS信息和车牌号等信息
		if (StringUtils.isNotEmpty(assTrailCarDVO.getPrjPrdDtlId())) {
            PrjPrdDtlGpsQueryCondition prjPrdDtlGpsQC = new PrjPrdDtlGpsQueryCondition();
            prjPrdDtlGpsQC.setPrjDtlId(assTrailCarDVO.getPrjPrdDtlId());
            // gps
            List<PrjPrdDtlGpsVO> gpsVOS = this.prjPrdDtlGpsService.searchList(prjPrdDtlGpsQC);
            BaseLogUtils.newLogger("根据拖车查询gps信息").setKeys("赎回id=" + assDealRedeemVO.getId(), "根据拖车查询的gps信息为：" + JSON.toJSONString(gpsVOS)).info();
            if (CollectionUtils.isNotEmpty(gpsVOS)) {
                for (PrjPrdDtlGpsVO gps : gpsVOS) {
                    if (1 == gps.getSerialNo()) {
                        view.addObject("gps1", gps.getGpsCardNo());
                        if (StringUtils.isNotEmpty(gps.getInstaller())) {
                            view.addObject("installer", gps.getInstaller());
                        }
                        if (null != gps.getInstallDt()) {
                            view.addObject("installDt", gps.getInstallDt());
                        }
                        if (StringUtils.isNotEmpty(gps.getGpsRem())) {
                            view.addObject("gpsRem", gps.getGpsRem());
                        }
                    } else if (2 == gps.getSerialNo()) {
                        view.addObject("gps2", gps.getGpsCardNo());
                        if (StringUtils.isNotEmpty(gps.getInstaller())) {
                            view.addObject("installer", gps.getInstaller());
                        }
                        if (null != gps.getInstallDt()) {
                            view.addObject("installDt", gps.getInstallDt());
                        }
                        if (StringUtils.isNotEmpty(gps.getGpsRem())) {
                            view.addObject("gpsRem", gps.getGpsRem());
                        }
                    } else if (3 == gps.getSerialNo()) {
                        view.addObject("gps3", gps.getGpsCardNo());
                        if (StringUtils.isNotEmpty(gps.getInstaller())) {
                            view.addObject("installer", gps.getInstaller());
                        }
                        if (null != gps.getInstallDt()) {
                            view.addObject("installDt", gps.getInstallDt());
                        }
                        if (StringUtils.isNotEmpty(gps.getGpsRem())) {
                            view.addObject("gpsRem", gps.getGpsRem());
                        }
                    }
                }
            }
            // 项目产品明细
            PrjPrdDtlVO prjPrdDtlVO = this.prjPrdDtlService.selectById(assTrailCarDVO.getPrjPrdDtlId());
            if (null != prjPrdDtlVO) {
                view.addObject("vin", prjPrdDtlVO.getVin());
            }
            // 项目产品上牌信息
            PrjPrdLicInfoVO prjPrdLicInfoVO = this.prjPrdLicInfoService.selectById(assTrailCarDVO.getPrjPrdDtlId());
            if (null != prjPrdLicInfoVO) {
                view.addObject("vehNo", prjPrdLicInfoVO.getVehNo());
            }
        }
		// 找到发起的是启用支付表
		String paySchId = String.valueOf(assTrailCarDVO.getPaySchId());
        if (StringUtils.isNotEmpty(paySchId)) {
            List<PrjPrdPaySchMDTO> prjPrdPaySchMDTOS = this.prjPrdPaySchMService.searchTheSamePrdOtherPaySchMList(Long.valueOf(paySchId));
            for (PrjPrdPaySchMDTO prjPrdPaySchMDTO : prjPrdPaySchMDTOS) {
                if (PrjPrdPaySchMConstant.PAY_SCH_TYP_CD_WS.equals(prjPrdPaySchMDTO.getPaySchTypCd())) {
                    // 现在查出的-1支付表
                    String wsPaySchId = prjPrdPaySchMDTO.getId().toString();
                    view.addObject("wsPaySchId", wsPaySchId);
                }
            }
        }
		view.addObject("paySchId", paySchId);
		view.addObject("isDetail", isDetail);
        view.addObject("redeemTypCd", assDealRedeemVO.getRedeemTypeCd());
		//赎回流程-查询绑定资金数据
		view = findBindFundData(request, view, paySchId, redeem_Id);

		return view;
	}

	//查询绑定资金数据
	public ModelAndView findBindFundData(HttpServletRequest request, ModelAndView mav, String paySchId, String dataId) {
		this.prepare(request, mav);
		String bizTyp = request.getParameter("bizTyp");//业务类型 3
		mav.addObject("bizTyp", bizTyp);
		if (StringUtils.isEmpty(dataId) || StringUtils.isEmpty(bizTyp)) {
			return mav;
		}

		//查询支付表信息
		PrjPrdPaySchMVO paySchMVO = this.prjPrdPaySchMService.selectById(Long.parseLong(paySchId));
		if (paySchMVO == null) {
			return mav;
		}
		//查询项目信息
		PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(paySchMVO.getPrjId());
		if (prjBscInfoVO == null) {
			return mav;
		}

		CapFundVO fundVO = new CapFundVO();//来款信息
		fundVO.setRelationPayId(Long.valueOf(paySchId));//资金管理关联业务ID
		fundVO.setIdentifyOperator(CurrentThreadContext.getCurrentUserId());//认款人ID
		fundVO.setIdentifyOperatorNm(CurrentThreadContext.getCurrentUserName());//认款人名称
		fundVO.setIdentifyTime(new Date());//认款时间 add时会修改
		//默认财务收款账户、账号
		fundVO.setAcceptName(InsuranceConstant.CODE_FC_ACCEPT_ACCOUNT_NM);//收款账户
		fundVO.setAcceptCode(InsuranceConstant.CODE_FC_ACCEPT_ACCOUNT_CD);//收款账号
		fundVO.setPaySchNo(paySchMVO.getPaySchNo());

		//查询客户名称，客户ID,所属事业部
		fundVO.setCstId(paySchMVO.getCstId());
		fundVO.setCstNm(prjBscInfoVO.getCstNm());
		fundVO.setFundBelongOrgCd(prjBscInfoVO.getBuOrgCd());
		fundVO.setComeName(prjBscInfoVO.getCstNm());

		//查询待核销支付表明细列表 支付表号、客户ID、期次、费用类型
		mav.addObject("paySchId", paySchMVO.getId());
		mav.addObject("cstId", fundVO.getCstId());
		mav.addObject("cstNm", prjBscInfoVO.getCstNm());

		//交易日期与实际到账日期默认流程发起时间
		Date flowStartTm = this.capFundService.getFlowStartTime(Long.parseLong(dataId), bizTyp);
		if (null != flowStartTm) {
			fundVO.setAcceptDate(DateUtils.formatDate(flowStartTm, DateUtils.YYYY_MM_DD));
			fundVO.setAcceptActualDate(DateUtils.formatDate(flowStartTm, DateUtils.YYYY_MM_DD));
			fundVO.setAcceptDates(DateUtils.formatDateToString(fundVO.getAcceptDate(), DateUtils.YYYY_MM_DD));
			fundVO.setAcceptActualDates(DateUtils.formatDateToString(fundVO.getAcceptActualDate(), DateUtils.YYYY_MM_DD));
		}
		mav.addObject("capFundVO", fundVO);
		mav.addObject("stlDtDisableFlag", 0);// 结清时间是否显示，0-否，1-是
		return mav;
	}

	/**
	 * 加载数据字典数据、传值等
	 *
	 * @param request
	 * @param mav
	 */
	public void prepare(HttpServletRequest request, ModelAndView mav) {
		// 事业部
		List<KeyValueVO> orgList = this.cstBscInfoService.searchBusinessOrgList();
		mav.addObject("fundBelongOrgCdList", JSON.toJSONString(orgList));
	}

	/**
	 * 新增转优车信息主表数据
	 * 同时发起转优车申请流程
	 */
	@RequestMapping(value = "/addOptimalInfo.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object addOptimalInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		//获取页面参数
		String masterId = request.getParameter("tcMasterId");
		String detailId = request.getParameter("tcDetailId");
		String prjId = request.getParameter("prjId");
        // 启用的支付表id
		String paySchId = request.getParameter("enabledPaySchId");
        // 启用的支付表号
		String paySchNo = request.getParameter("enabledPaySchNo");
		String cstId = request.getParameter("cstId");
		String cstNm = request.getParameter("cstNm");
		String buOrgCd = request.getParameter("buOrgCd");
		String dealDesc = request.getParameter("dealDesc");
		String prjPrdDtlId = request.getParameter("prjPrdDtlId");
		String businessType = request.getParameter("businessType");
		String prjTypCd = request.getParameter("prjTypCd");
		String prjNm = request.getParameter("prjNm");
		String orgName = request.getParameter("orgName");
		// 合同编号
		String contNo = request.getParameter("contNo4Save");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		AssDealCarVO entity = new AssDealCarVO();
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("orgCode",buOrgCd);//事业部简称-流程使用
        PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(Long.valueOf(prjId));
        if (null == prjBscInfoVO) {
            BaseLogUtils.newLogger("查询项目基础信息失败").setKeys("prjId:" + prjId, "paySchId:" + paySchId).info();
            throw new BaseException("查询项目基础信息失败");
        }

        // 设置节点处理人为客户经理
        String[] str = {String.valueOf(prjBscInfoVO.getCstMgrId())};
        map.put("cstMgrAssignee", str);
		//map.put("orgCode","ZK");//事业部简称-流程使用
		try {
			//设置主表实体属性
			if(StringUtils.isNotEmpty(masterId)){
				entity.setMasterId(Long.parseLong(masterId));
			}
			if(StringUtils.isNotEmpty(detailId)){
				entity.setDetailId(Long.parseLong(detailId));
			}
			if(StringUtils.isNotEmpty(prjId)){
				entity.setPrjId(Long.valueOf(prjId));
			}
			if(StringUtils.isNotEmpty(paySchId)){
				entity.setPaySchId(Long.valueOf(paySchId));
			}
			if(StringUtils.isNotEmpty(cstId)){
				entity.setCstId(Long.parseLong(cstId));
			}
			// 流程过期时间（发起的第2天算第1天，7天过期，故加8天是过期时间）
			Date expireTime = DateUtils.getDateAddDate(DateUtils.getCurrentDate(DateUtils.YYYY_MM_DD), 5, 8);
			entity.setExpireTime(expireTime);
			entity.setCstNm(cstNm);
			entity.setPaySchNo(paySchNo);
			entity.setDealDesc(dealDesc);
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setCrtTm(new Date());
			entity.setIsDel(BaseConstant.IS_YESNO_NO);
            entity.setFlowStatusCd(InterfaceConstants.FLOW_STATUS_CD_2);
			// 合同编号
			entity.setContNo(contNo);
			// 当前所在节点
            entity.setTaskDefKey(DealCarFlowEnum.FLOW_0001.getTaskDefKey());
            /**
             * 为避免脏读先提交新增转优车数据的事务
             */
            // 保存转优车信息
			Long id = this.assDealCarService.add(entity);
			if(null != id){
				//设置流程参数
				AssTrailCarDQueryCondition qc = new AssTrailCarDQueryCondition();
				qc.setId(id);//转优车主表ID
				qc.setOrgName(orgName);//项目所属事业部名称
				qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
				qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
				qc.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());//当前登录人事业部代码
				qc.setUsrId(CurrentThreadContext.getCurrentUserId());
				qc.setUsrNm(CurrentThreadContext.getCurrentUserName());
				qc.setFlowModelType(FlowConstant.FLOW_MODEL_TYP_ASS_YC);//"020"拖车管理转优车
				qc.setFlow_Map(map);//附加参数
				if(StringUtils.isNotEmpty(prjPrdDtlId)){//项目产品明细表ID
					qc.setPrjPrdDtlId(Long.parseLong(prjPrdDtlId));
				}
				if(StringUtils.isNotEmpty(prjId)){//项目基础信息表ID
					qc.setPrjId(Long.parseLong(prjId));
				}
				if(StringUtils.isNotEmpty(cstId)){//客户ID
					qc.setCstId(Long.parseLong(cstId));
				}
				qc.setBusinessType(businessType);
				qc.setPrjTypCd(prjTypCd);
				qc.setPrjNm(prjNm);
				qc.setCstNm(cstNm);
				//发起转优车申请流程
				result = this.assTrailCarMService.addTrailCarApply(qc);
				//发起成功修改拖车明细表状态
				if(result.getSuccess()==1){
					AssTrailCarDVO dEntity = new AssTrailCarDVO();
					if(StringUtils.isEmpty(detailId)){
					    result.setSuccess(BaseConstant.IS_YESNO_NO);
					    result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
					    return result;
					}else{
					    // 流程实例id和流程编号存进去
                        AssDealCarDTO assDealCarDTO = (AssDealCarDTO)result.getData();
                        entity.setId(id);
                        entity.setProcId(assDealCarDTO.getProcId());
                        entity.setProcNo(assDealCarDTO.getProcNo());
                        assDealCarService.modify(entity);
                        dEntity.setId(Long.parseLong(detailId));
						dEntity.setDealTypeCd("3");//处置方式：转优车
						dEntity.setDealStsCd("10");//处置状态：转优车中
						boolean succ = this.assTrailCarDService.modify(dEntity);
						if(!succ){
						    BaseLogUtils.newLogger("修改拖车明细表状态失败").setKeys("detailId:" + detailId).info();
						}
                        // 设置拖车转优车中状态
                        ProductStatusLogVO productStatusLogVO = new ProductStatusLogVO();
                        productStatusLogVO.setPaySchId(Long.valueOf(paySchId));
                        productStatusLogVO.setPrjPrdId(Long.valueOf(prjPrdDtlId));
                        productStatusLogVO.setCurrentStatus(InterfaceConstants.PAY_STATUS_CD_S01060203);
                        productStatusLogVO.setOpCode(InterfaceConstants.OP_CODE_OP0028);
                        productStatusLogVO.setProcessInstanceCode(assDealCarDTO.getProcNo());
                        productStatusLogVO.setProcessInstanceId(assDealCarDTO.getProcId());
                        this.assTrailCarMService.updateYQPrdStsCdByFlow(productStatusLogVO);
					}
				}
				//设置转优车主表ID
				result.setData(id);
			}else{
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("发起转优车申请流程失败！");
				BaseLogUtils.newLogger("新增转优车信息主表数据失败").setKeys("id:" + id, "] DATA:" + JSONObject.toJSONString(entity)).info();
			}
		}catch (BaseException ex) {
			BaseLogUtils.newLogger("新增转优车信息主表数据失败").setThrowable(ex).setKeys("DATA:" + JSONObject.toJSONString(entity)).error(LogExceptionEnum.COMMON_CODE_0002);
			throw ex;
		}catch (Exception ex) {
            BaseLogUtils.newLogger("新增转优车信息主表数据失败").setThrowable(ex).setKeys("DATA:" + JSONObject.toJSONString(entity)).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		}
		return result;
	}
	/**
	 * 查询处置-转优车信息表  kfc
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getDealCarById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getDealCarById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		
		try {
			AssDealCarVO vo = this.assDealCarService.selectById(Long.valueOf(id));
			// 查询过户费费用项
			AssDealCarCostQueryCondition qc = new AssDealCarCostQueryCondition();
			qc.setCarId(Long.parseLong(id));
			qc.setCostTypeCd("1");
			Pager pager = new Pager();
			pager.setCondition(qc);
			List<AssDealCarCostDTO> list = (List<AssDealCarCostDTO>) this.assDealCarCostService.findAssDealCarCostListByPage(pager).getResultList();
			if (CollectionUtils.isNotEmpty(list)) {
                vo.setFeeAmt(list.get(0).getCostAmt());
            }
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				return result;
			}
			result.setData(vo);
		}catch(BaseException ex) {
			BaseLogUtils.newLogger("获取转优车信息失败").setKeys("id:" + id).setThrowable(ex).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
			throw ex;
		}catch(Exception ex) {
            BaseLogUtils.newLogger("获取转优车信息失败").setKeys("id:" + id).setThrowable(ex).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		}
		return result;
	}
	/**
	 * 更新转优车信息主表数据
	 */
	@RequestMapping(value = "/updateOptimalInfo.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object updateOptimalInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		//获取页面参数
		String id = request.getParameter("optimal_Id");
		String detailId =  request.getParameter("tcDetailId");
		String dealDesc = request.getParameter("dealDesc");
        // 转优车保底价
		String dealBaseAmt =  request.getParameter("dealBaseAmt");
        // 亏损%
		String gainLoassScale = request.getParameter("gainLoassScale");
		// 节点标识
		String flag = request.getParameter("flag");
		// 是否可过户
		String isAssign = request.getParameter("isAssign");
		// 过户费
		String assignAmt = request.getParameter("assignAmt");
		// 提户情况
        String assAccTyp = request.getParameter("assAccTyp");
        // 资产管理员id
        String assManager = request.getParameter("assManager");
        // 是否异地提档
        String isDiffPlace = request.getParameter("isDiffPlace");
        // 备注
        String remark = request.getParameter("remark");
        // 收件人
        String recipientName = request.getParameter("recipientName");
        // 接收方式
        String receiveType = request.getParameter("receiveType");
        // 联系电话
        String contactNumber = request.getParameter("contactNumber");
        // 快递公司
        String express = request.getParameter("express");
        // 快递单号
        String expressNumber = request.getParameter("expressNumber");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		AssDealCarVO entity = null;
		AssDealCarCostVO assDealCarCostVO = null;
		try {
			// 设置主表实体属性
			if(StringUtils.isEmpty(id)){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
				return result;
			}
			entity = new AssDealCarVO();
			entity.setId(Long.parseLong(id));
			entity.setRemark(remark);
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setMdfTm(new Date());
			// 提交修改数据前的校验
            DataResultVO resultVO = validateBeforeUpdate(result, flag, isAssign, isDiffPlace, assignAmt, assAccTyp, assManager, recipientName, receiveType, contactNumber, express, expressNumber);
            if (BaseConstant.IS_YESNO_NO == resultVO.getSuccess()) {
                return resultVO;
            }
            boolean success = false;
			switch (flag) {
                case "1":
                    // 提交过户资料
                    entity.setIsDiffPlace(Integer.parseInt(isDiffPlace));
                    entity.setIsAssign(Integer.valueOf(isAssign));
                    // 提户情况
                    if (StringUtils.isNotEmpty(assAccTyp)) {
                        entity.setAssAccTyp(Integer.parseInt(assAccTyp));
                    } else {
                        assDealCarService.modify4Null(entity);
                    }
                    result = updateAssDealCarCost(Long.parseLong(id), result, assDealCarCostVO, assignAmt);
                    //更新转优车信息
                    success = this.assDealCarService.modify(entity);
                    if (!success) {
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
                        return result;
                    }
                    break;
                case "2":
                    // 省总/大区总审核
                    entity.setIsDiffPlace(Integer.parseInt(isDiffPlace));
                    // 是否可过户（选是）
                    entity.setIsAssign(Integer.valueOf(isAssign));
                    // 提户情况
                    if (StringUtils.isNotEmpty(assAccTyp)) {
                        entity.setAssAccTyp(Integer.parseInt(assAccTyp));
                    }
                    entity.setDealDesc(dealDesc);
                    //更新转优车信息
                    success = this.assDealCarService.modify(entity);
                    if (!success) {
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
                        return result;
                    }
                    if (StringUtils.isNotEmpty(assignAmt)) {
                        result = updateAssDealCarCost(Long.parseLong(id), result, assDealCarCostVO, assignAmt);
                    }
                    break;
                case "3":
                    // 优车事业部审批指定过户人
                    entity.setManageId(assManager);
                    success = this.assDealCarService.modify(entity);
                    if (!success) {
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
                        return result;
                    }
                    break;
                case "4":
                    // 客户经理添加邮寄信息
                    entity.setRecipientName(recipientName);
                    entity.setReceiveType(receiveType);
                    entity.setContactNumber(contactNumber);
                    entity.setExpressNumber(expressNumber);
                    entity.setExpress(express);
                    success = this.assDealCarService.modify(entity);
                    if (!success) {
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
                        return result;
                    }
                    break;
                case "5":
                    // 资产管理员/过户人办理过户
                    break;
                case "6":
                    // 优车系统管理员审核是否完成过户
                    if(StringUtils.isNotEmpty(dealBaseAmt)){
                        entity.setDealBaseAmt(DecimalUtils.convertYuanToFen(Double.valueOf(dealBaseAmt)));
                    }
                    entity.setIsAssign(Integer.valueOf(isAssign));
                    //更新转优车信息
                    success = this.assDealCarService.modify(entity);
                    if(!success){
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo( SysLogConstant.LOG_CMM_UPDATE_FAIL);
                        return result;
                    }
                    if (StringUtils.isEmpty(detailId)) {
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
                        return result;
                    }
                    if (StringUtils.isNotEmpty(gainLoassScale)) {
                        AssTrailCarDVO trailCarEntity = new AssTrailCarDVO();
                        trailCarEntity.setId(Long.valueOf(detailId));
                        trailCarEntity.setGainLoassScale(Double.valueOf(gainLoassScale));
                        trailCarEntity.setMdfTm(new Date());
                        trailCarEntity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
                        //更新拖车明细信息
                        success = this.assTrailCarDService.modify(trailCarEntity);
                        if(!success){
                            result.setSuccess(BaseConstant.IS_YESNO_NO);
                            result.setInfo( SysLogConstant.LOG_CMM_UPDATE_FAIL);
                            return result;
                        }
                    }
                    break;
                case "7":
                    // 优车资产经理审批是否完成过户
                    if(StringUtils.isNotEmpty(isAssign)){
                        entity.setIsAssign(Integer.valueOf(isAssign));
                    }
                    //更新转优车信息
                    success = this.assDealCarService.modify(entity);
                    if(!success){
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo( SysLogConstant.LOG_CMM_UPDATE_FAIL);
                        return result;
                    }
                    break;
                default:
                    break;
            }
		}catch (BaseException ex) {
			BaseLogUtils.newLogger("更新转优车信息失败").setThrowable(ex).setKeys("DATA:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
			throw ex;
		}catch (Exception ex) {
            BaseLogUtils.newLogger("更新转优车信息失败").setThrowable(ex).setKeys("DATA:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		}
		return result;
	}

    /**
     * 对已有的过户费进行修改，没有的过户费新增
     * @param id
     */
	private DataResultVO updateAssDealCarCost(Long id, DataResultVO result, AssDealCarCostVO assDealCarCostVO, String assignAmt) {
        AssDealCarCostQueryCondition qc = new AssDealCarCostQueryCondition();
        qc.setCarId(Long.valueOf(id));
        qc.setCostTypeCd("1");
        List<AssDealCarCostDTO> assDealCarCostDTOS = this.assDealCarCostService.searchAssDealCarCostList(qc);
        if (CollectionUtils.isNotEmpty(assDealCarCostDTOS)) {
            AssDealCarCostDTO assDealCarCostDTO = assDealCarCostDTOS.get(0);
            if (StringUtils.isNotEmpty(assignAmt)) {
                assDealCarCostDTO.setCostAmt(DecimalUtils.convertYuanToFen(Double.valueOf(assignAmt)));
            } else {
                assDealCarCostDTO.setCostAmt(0L);
            }
            boolean success = this.assDealCarCostService.modify(AssDealCarCostVOTransform.toVO(assDealCarCostDTO));
            if (false == success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_ADD_FAIL);
                return result;
            }
        } else {
            assDealCarCostVO = new AssDealCarCostVO();
            assDealCarCostVO.setCarId(id);
            // 过户费类型：1
            assDealCarCostVO.setCostTypeCd("1");
            if (StringUtils.isNotEmpty(assignAmt)) {
                assDealCarCostVO.setCostAmt(DecimalUtils.convertYuanToFen(Double.valueOf(assignAmt)));
            } else {
                assDealCarCostVO.setCostAmt(0L);
            }
            Long succ = this.assDealCarCostService.saveAssDealCarCost(assDealCarCostVO);
            if (StringUtils.isEmpty(succ)) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
                return result;
            }
        }
        return result;
    }

    /**
     * 修改数据之前的校验
     * @param result 返回结果
     * @param flag 节点标识
     * @param isAssign 是否可过户
     * @param isDiffPlace 是否异地提档
     * @param assignAmt 过户费
     * @param assAccTyp 提户情况
     * @param assManager 资产管理员
     * @param recipientName 收件人姓名
     * @param receiveType 接收方式
     * @param contactNumber 联系电话
     * @param express 快递公司
     * @param expressNumber 快递单号
     * @return
     */
	private DataResultVO validateBeforeUpdate(DataResultVO result, String flag, String isAssign, String isDiffPlace, String assignAmt, String assAccTyp, String assManager, String recipientName, String receiveType, String contactNumber, String express, String expressNumber) {
        switch (flag) {
            case "1":
                if (StringUtils.isEmpty(isAssign)) {
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo("请选择是否可过户");
                } else if (StringUtils.isEmpty(isDiffPlace)) {
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo("请选择是否异地提档");
                } else if (BaseConstant.IS_YESNO_YES_STR.equals(isAssign)) {
                    if (StringUtils.isEmpty(assAccTyp)) {
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo("请选择提户情况");
                    } else if (StringUtils.isEmpty(assignAmt)) {
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo("请填写过户费");
                    }
                }
                break;
            case "2":
                // 省总/大区总审核
                if (StringUtils.isEmpty(isAssign)) {
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo("请选择是否可过户");
                } else if (StringUtils.isEmpty(isDiffPlace)) {
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo("请选择是否异地提档");
                } else if (BaseConstant.IS_YESNO_YES_STR.equals(isAssign)) {
                    if (StringUtils.isEmpty(assAccTyp)) {
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo("请选择提户情况");
                    } else if (StringUtils.isEmpty(assignAmt)) {
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo("请填写过户费");
                    }
                }
                break;
            case "3":
                // 优车事业部审批指定过户人
                if (StringUtils.isEmpty(assManager)) {
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo("请选择资产管理员");
                }
                break;
            case "4":
                // 客户经理添加邮寄信息
                if (StringUtils.isEmpty(recipientName)) {
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo("请填写收件人");
                } else if (StringUtils.isEmpty(receiveType)) {
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo("请选择接收方式");
                } else if (BaseConstant.IS_YESNO_YES_STR.equals(receiveType)) {
                    // 邮寄
                    if (StringUtils.isEmpty(express)) {
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo("请填写快递公司");
                    } else if (StringUtils.isEmpty(expressNumber)) {
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo("请填写快递单号");
                    }
                }
                if (StringUtils.isEmpty(contactNumber)) {
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo("请填写联系电话");
                }
                break;
            case "5":
                // 资产管理员/过户人办理过户

                break;
            case "6":
                // 优车系统管理员审核是否完成过户
                if (StringUtils.isEmpty(isAssign)) {
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo("请选择是否可过户");
                }
                break;
            case "7":
                // 优车资产经理审批是否完成过户
                if (StringUtils.isEmpty(isAssign)) {
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo("请选择是否可过户");
                }
                break;
            default:
                break;
        }
        return result;
    }

    /**
     * 初始化维护过户方案资料是否完整
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/initIsComplete.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initIsComplete(HttpServletRequest request) {
        String id = request.getParameter("id");
        AssFileLogQC qc = new AssFileLogQC();
        qc.setOptId(Long.parseLong(id));
        // 查询文件
        List<AssFileLogVO> list = this.assFileLogService.selectList(qc);
        if (CollectionUtils.isNotEmpty(list)) {
            return list;
        } else {
            return new ArrayList<AssFileLogVO>();
        }
    }

	/**
	 * 初始化维护过户方案资料grid
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/initAssProFileGrid.do", method = {RequestMethod.GET})
	@ResponseBody
	public Object initAssProFileGrid(HttpServletRequest request) {
		String id = request.getParameter("id");
		// 提户情况（通过提户情况判断需要上传哪些资料项）
		String assAccTyp = request.getParameter("assAccTyp");
		// 必填校验标记
        String validate = request.getParameter("validate");
		if (StringUtils.isEmpty(assAccTyp)) {
		    return new ListPageVO<AssProFileVO>();
        }
		// 文件查询条件
		AssProFileQC condition = new AssProFileQC();
		condition.setOptimalId(Long.valueOf(id));
		condition.setOrgCd(AssFileConstant.ASS_PRO_ORG_CD);
		condition.setSysCd(AssFileConstant.ASS_PRO_SYS_CD);
		List<String> cfgCdList = new ArrayList<>();
		cfgCdList.add(AssFileConstant.ASS_PRO_FILE_CFG_CD_006);
		condition.setCfgCdList(cfgCdList);
        List<String> cfgCdDtlList = new ArrayList<>();
		if (BaseConstant.IS_YESNO_YES_STR.equals(assAccTyp)) {
            cfgCdDtlList.add(AssFileConstant.ASS_PRO_CFGDTLCD_NEW_10);
            cfgCdDtlList.add(AssFileConstant.ASS_PRO_CFGDTLCD_NEW_20);
            cfgCdDtlList.add(AssFileConstant.ASS_PRO_CFGDTLCD_NEW_30);
            cfgCdDtlList.add(AssFileConstant.ASS_PRO_CFGDTLCD_NEW_40);
        } else if (BaseConstant.IS_YESNO_NO_STR.equals(assAccTyp)) {
            cfgCdDtlList.add(AssFileConstant.ASS_PRO_CFGDTLCD_NEW_10);
            cfgCdDtlList.add(AssFileConstant.ASS_PRO_CFGDTLCD_NEW_20);
            cfgCdDtlList.add(AssFileConstant.ASS_PRO_CFGDTLCD_NEW_50);
            cfgCdDtlList.add(AssFileConstant.ASS_PRO_CFGDTLCD_NEW_60);
        }
		condition.setCfgCdDtlList(cfgCdDtlList);
		// 查询文件
		List<AssProFileVO> list = this.assDealCarService.searchAssProCfgDtlAndFileCfg(condition);
		// 做必填校验的判断
        if (BaseConstant.IS_YESNO_YES_STR.equals(validate)) {
            for (AssProFileVO file : list) {
                if (StringUtils.isEmpty(file.getFileId())) {
                    if (BaseConstant.IS_YESNO_YES_STR.equals(assAccTyp)) {
                        if (AssFileConstant.ASS_PRO_CFGDTLCD_NEW_10.equals(file.getCfgDtlCd()) || AssFileConstant.ASS_PRO_CFGDTLCD_NEW_20.equals(file.getCfgDtlCd()) ||
                                AssFileConstant.ASS_PRO_CFGDTLCD_NEW_30.equals(file.getCfgDtlCd()) || AssFileConstant.ASS_PRO_CFGDTLCD_NEW_40.equals(file.getCfgDtlCd()))
                        return BaseConstant.IS_YESNO_NO_STR + "_" + file.getDatNm();
                    } else if (BaseConstant.IS_YESNO_NO_STR.equals(assAccTyp)) {
                        if (AssFileConstant.ASS_PRO_CFGDTLCD_NEW_10.equals(file.getCfgDtlCd()) || AssFileConstant.ASS_PRO_CFGDTLCD_NEW_20.equals(file.getCfgDtlCd()) ||
                                AssFileConstant.ASS_PRO_CFGDTLCD_NEW_50.equals(file.getCfgDtlCd()) || AssFileConstant.ASS_PRO_CFGDTLCD_NEW_60.equals(file.getCfgDtlCd()))
                            return BaseConstant.IS_YESNO_NO_STR + "_" + file.getDatNm();
                    }
                }
            }
        }
		if (CollectionUtils.isNotEmpty(list)) {
			return new ListPageVO<AssProFileVO>(list, list.size());
		} else {
			return new ListPageVO<AssProFileVO>();
		}
	}

    /**
     * 在文件接收SYS_UL_FILE_REC表中增加文件上传记录
     *
     * @param request
     */
    @RequestMapping(value = "/uploadAssProFile.do", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object uploadAssProFile(HttpServletRequest request) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_FILE_UPLOAD_SUCC);
        String fileParams = request.getParameter("fileParams");
        String cfgCd = request.getParameter("cfgCd");
        String cfgDtlCd = request.getParameter("cfgDtlCd");
        String orgCd = request.getParameter("orgCd");
        String id = request.getParameter("id");
        if (StringUtils.isBlank(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_FILE_UPLOAD_FAIL);
        } else {
            boolean flag = this.sysUlFilesRecService.addAttchmnt(id, fileParams, cfgCd, cfgDtlCd, "ASS_DEAL_CAR", null, null, null, false, orgCd);
            if (!flag) {
                BaseLogUtils.newLogger("上传维护过户方案资料文件失败").setKeys("id:" + id, "cfgCd:" + cfgCd, "cfgDtlCd:" + cfgDtlCd, "fileParams:" + JSON.toJSONString(fileParams));
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_FILE_UPLOAD_FAIL);
                return result;
            }
        }
        return result;
    }

    /**
     * 点击是否齐全将转优车文件的表的数据修改或新增
     *
     * @param request
     */
    @RequestMapping(value = "/setAssFileLog.do", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object setAssFileLog(HttpServletRequest request) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_FILE_UPLOAD_SUCC);
        String optimalId = request.getParameter("optimal_Id");
        // 转优车维护过户方案上传资料时，点击是否齐全，在拖车文件表中修改或新增数据
        String isComplete = request.getParameter("isComplete");
        // 文件配置明细CD
        String cfgDtlCd = request.getParameter("cfgDtlCd");
        AssFileLogVO vo = null;
        AssFileLogQC qc = new AssFileLogQC();
        qc.setOptId(Long.parseLong(optimalId));
        qc.setCfgDtlCd(cfgDtlCd);
        List<AssFileLogVO> list = assFileLogService.selectList(qc);
        BaseLogUtils.newLogger("获取之前的转优车资料配置").setKeys("optimalId:" + optimalId, "list:" + JSON.toJSONString(list)).info();
        if (CollectionUtils.isNotEmpty(list)) {
            vo = list.get(0);
            vo.setIsComplete(isComplete);
            vo.setMdfTm(new Date());
            vo.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
            boolean flag = assFileLogService.modify(vo);
            if (!flag) {
                BaseLogUtils.newLogger("新增转优车资料数据失败").setKeys("optimalId:" + JSON.toJSONString(optimalId)).info();
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_FILE_UPLOAD_FAIL);
                return result;
            }
            BaseLogUtils.newLogger("新增转优车资料数据成功").setKeys("vo:" + JSON.toJSONString(vo)).info();
        } else {
            vo = new AssFileLogVO();
            vo.setOptId(Long.parseLong(optimalId));
            vo.setCfgDtlCd(cfgDtlCd);
            vo.setIsComplete(isComplete);
            vo.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
            vo.setCrtTm(new Date());
            assFileLogService.add(vo);
            BaseLogUtils.newLogger("新增转优车资料数据成功").setKeys("optimalId:" + JSON.toJSONString(optimalId)).info();
        }
        return result;
    }
	
	/**
	 * 到转优车流程附加信息页面
	 */
	@RequestMapping(value = "/toOptimalViewPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toOptimalViewPage(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		//获取页面标识和拖车主表ID
		String flag = request.getParameter("flag");
		String optimal_Id = request.getParameter("optimal_Id");
		// 仅查看的按钮
        String viewFlag = request.getParameter("viewFlag");
		AssDealCarVO vo  = this.assDealCarService.selectById(Long.valueOf(optimal_Id));
		ModelAndView view = new ModelAndView("ass/assTrailCarM/assOptimalApplyView");
        // 借款类型
        List<KeyValueVO> finLoanTypList = this.sysDictionaryApiService.getKvList(FinLoanConstant.FIN_LOAN_TYP_DIDC, FinLoanConstant.SYS_CD, FinLoanConstant.ORG_CD);
        view.addObject("finLoanTypList", JSON.toJSONString(finLoanTypList));
		view.addObject("flag", flag);
		view.addObject("optimal_Id", optimal_Id);
		view.addObject("tcMasterId", vo.getMasterId());//申请表id
		view.addObject("tcDetailId", vo.getDetailId());//明细id
        // 启用的支付表id
		view.addObject("paySchId", vo.getPaySchId());
        if (StringUtils.isNotEmpty(vo.getPaySchId())) {
            List<PrjPrdPaySchMDTO> prjPrdPaySchMDTOS = this.prjPrdPaySchMService.searchTheSamePrdOtherPaySchMList(Long.valueOf(vo.getPaySchId()));
            for (PrjPrdPaySchMDTO prjPrdPaySchMDTO : prjPrdPaySchMDTOS) {
                if (PrjPrdPaySchMConstant.PAY_SCH_TYP_CD_WS.equals(prjPrdPaySchMDTO.getPaySchTypCd())) {
                    // 现在查出的我司支付表
                    String wsPaySchId = prjPrdPaySchMDTO.getId().toString();
                    view.addObject("wsPaySchId", wsPaySchId);
                    view.addObject("wsPaySchNo", prjPrdPaySchMDTO.getPaySchNo());
                }
            }
        }
        Date expireTime = vo.getExpireTime();
        // 计算页面显示的灯是什么颜色（大于等于4小于等于7的是蓝灯；小于等于3是黄灯）
        long daysBetweenTwoDates = DateUtils.getDaysBetweenTwoDates(DateUtils.getCurrentDate(DateUtils.YYYY_MM_DD), expireTime);
        view.addObject("light", daysBetweenTwoDates);
        view.addObject("viewFlag", viewFlag);
        view.addObject("prjPrdId", vo.getPrjPrdId());//项目产品id
		view.addObject("sysDate", DateUtils.formatDateToString(new Date(), DateUtils.YYYY_MM_DD));
		view.addObject("loginUsrNm", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 新增优车处置信息主表数据
	 * 同时发起优车处置申请流程
	 */
	@RequestMapping(value = "/addYCDealInfo.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object addYCDealInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		// 校验诉讼状态
		String sueApplyId = request.getParameter("sueApplyId");
//		if (StringUtils.isNotEmpty(sueApplyId) && !"null".equals(sueApplyId	)) {
//			try {
//				assDealSellService.checkLawsuitSts(Long.parseLong(sueApplyId));
//			} catch (Exception e) {
//				result.setSuccess(BaseConstant.IS_YESNO_NO);
//				result.setInfo(e.getMessage());
//				return result;
//			}
//		}
		//获取页面参数
		String masterId = request.getParameter("tcMasterId");
		String detailId = request.getParameter("tcDetailId");
		String optimal_Id = request.getParameter("optimal_Id");
		// 提前获取的优车主键id
        String ycSellId = request.getParameter("ycSellId");
		String cstId = request.getParameter("cstId");
		String cstNm = request.getParameter("cstNm");
		String buyerTypeCd = request.getParameter("buyerTypeCd");
		String sellAmt = request.getParameter("sellAmt");
		String sellChannelCd = request.getParameter("sellChannelCd");
		String dataTypeCd = request.getParameter("dataTypeCd");
		String sellDesc = request.getParameter("sellDesc");
		String buOrgCd = request.getParameter("buOrgCd");
		String buyerNm = request.getParameter("buyerNm");
		String buyerCd = request.getParameter("buyerCd");
		String buyerTel = request.getParameter("buyerTel");
		String buyerCompanyNm = request.getParameter("buyerCompanyNm");
		String buyerCompanyContact = request.getParameter("buyerCompanyContact");
		String buyerCompanyTel = request.getParameter("buyerCompanyTel");
		String buyerCompanyCode = request.getParameter("buyerCompanyCode");
		String prjPrdDtlId = request.getParameter("prjPrdDtlId");
		String prjId = request.getParameter("prjId");
		String businessType = request.getParameter("businessType");
		String prjTypCd = request.getParameter("prjTypCd");
		String prjNm = request.getParameter("prjNm");
		String orgName = request.getParameter("orgName");
		// 判断拖车明细表的处置状态是否为已转优车和优车处置不通过
		AssTrailCarDVO assTrailCarDVO = this.assTrailCarDService.selectById(Long.valueOf(detailId));
        if (!(InterfaceConstants.DEAL_STATUS_CD_11.equals(assTrailCarDVO.getDealStsCd()) || InterfaceConstants.DEAL_STATUS_CD_15.equals(assTrailCarDVO.getDealStsCd()))) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("只有已转优车/优车处置不通过的才能申请!");
            return result;
        }
		AssDealSellVO entity = new AssDealSellVO();
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("orgCode",buOrgCd);//事业部简称-流程使用
		map.put("aucDeal", "0");
        // 加线程锁的key，判断第二次进来是否是该线程
        String key = "ass::deal:sellcode:lock:" + detailId;
        String requestId = RedisLock.randomValue(16);
        boolean lock = false;
		try {
			//设置主表实体属性
			if(StringUtils.isNotEmpty(masterId)){
				entity.setMasterId(Long.parseLong(masterId));
			}
			if(StringUtils.isNotEmpty(detailId)){
				entity.setDetailId(Long.parseLong(detailId));
			}
			if(StringUtils.isNotEmpty(optimal_Id) && StringUtils.isNotEmpty(dataTypeCd)){
				if(!"null".equals(optimal_Id) && "2".equals(dataTypeCd)){//优车事业部
					entity.setDataId(Long.parseLong(optimal_Id));

					AssDealCarVO assDealCarVO = assDealCarService.selectById(Long.parseLong(optimal_Id));
					// 1-已上拍未成交
					if (AssDealSellConstant.AUCTION_STS_CD_1.equals(assDealCarVO.getAuctionStsCd())) {
						AssDealSellQueryCondition condition = new AssDealSellQueryCondition();
						condition.setDataId(Long.parseLong(optimal_Id));
						condition.setSortName("crt_tm");
						condition.setSortOrder("desc");
						List<AssDealSellVO> assDealSellVOS = assDealSellService.searchAssDealSellList(condition);
						if (CollectionUtils.isNotEmpty(assDealSellVOS)) {
							entity.setAssessAmt(assDealSellVOS.get(0).getAssessAmt());
						}
						map.put("aucDeal", "1");
					} else {
                        map.put("aucDeal", "0");
                    }
				}
			}
            if(StringUtils.isNotEmpty(ycSellId)){
                entity.setId(Long.parseLong(ycSellId));
            }
			if(StringUtils.isNotEmpty(cstId)){
				entity.setCstId(Long.parseLong(cstId));
			}
			if(StringUtils.isNotEmpty(sellAmt)){//元转分
				entity.setSellAmt(DecimalUtils.convertYuanToFen(Double.valueOf(sellAmt)));
			}
			entity.setCstNm(cstNm);
			entity.setBuyerTypeCd(buyerTypeCd);
			entity.setSellChannelCd(sellChannelCd);
			entity.setDataTypeCd(dataTypeCd);
			entity.setSellDesc(sellDesc);
			entity.setBuyerNm(buyerNm);
			entity.setBuyerCd(buyerCd);
			entity.setBuyerTel(buyerTel);
			entity.setBuyerCompanyNm(buyerCompanyNm);
			entity.setBuyerCompanyContact(buyerCompanyContact);
			entity.setBuyerCompanyTel(buyerCompanyTel);
			entity.setBuyerCompanyCode(buyerCompanyCode);
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setCrtTm(new Date());
			entity.setIsDel(BaseConstant.IS_YESNO_NO);
			entity.setApplyNm(CurrentThreadContext.getCurrentUserName());
			
			//保存优车处置信息
			Long id = this.assDealSellService.add(entity);
			if(null != id){
				//设置流程参数
				AssTrailCarDQueryCondition qc = new AssTrailCarDQueryCondition();
				qc.setId(Long.parseLong(ycSellId));//优车处置主表ID
				qc.setOrgName(orgName);//项目所属事业部名称
				qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
				qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
				qc.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());//当前登录人事业部代码
				qc.setUsrId(CurrentThreadContext.getCurrentUserId());
				qc.setUsrNm(CurrentThreadContext.getCurrentUserName());
				qc.setFlowModelType(FlowConstant.FLOW_MODEL_TYP_ASS_DEAL_YC);//"019"优车处置
				qc.setFlow_Map(map);//附加参数
				if(StringUtils.isNotEmpty(prjPrdDtlId)){//项目产品明细表ID
					qc.setPrjPrdDtlId(Long.parseLong(prjPrdDtlId));
				}
				if(StringUtils.isNotEmpty(prjId)){//项目基础信息表ID
					qc.setPrjId(Long.parseLong(prjId));
				}
				if(StringUtils.isNotEmpty(cstId)){//客户ID
					qc.setCstId(Long.parseLong(cstId));
				}
				qc.setBusinessType(businessType);
				qc.setPrjTypCd(prjTypCd);
				qc.setPrjNm(prjNm);
				qc.setCstNm(cstNm);
				//发起优车处置申请流程
				result = this.assTrailCarMService.addTrailCarApply(qc);
				//发起成功修改拖车明细表状态
				if(result.getSuccess()==1){
					AssTrailCarDVO dEntity = new AssTrailCarDVO();
					if(StringUtils.isEmpty(detailId)){
					    result.setSuccess(BaseConstant.IS_YESNO_NO);
					    result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
					    return result;
					}else{
                        /**
                         * 加线程锁控制重复发起优车处置流程
                         */
                        lock = userRedisService.getDistributedLock(key, requestId, null);
                        if (!lock) {
                            BaseLogUtils.newLogger("正在修改拖车处置状态").setKeys("redis锁的key:" + key).info();
                            result.setSuccess(BaseConstant.IS_YESNO_NO);
                            result.setInfo("正在修改拖车处置状态，无法发起优车处置流程！");
                            return result;
                        }
						dEntity.setId(Long.parseLong(detailId));
						dEntity.setDealTypeCd("1");//处置方式：处置
						dEntity.setDealStsCd("13");//处置状态：优车处置中
						boolean succ = this.assTrailCarDService.modify(dEntity);
						if(!succ){
						    BaseLogUtils.newLogger("修改拖车明细表状态失败").setKeys("detailId:" + detailId, "DATA:" + JSONObject.toJSONString(dEntity)).info();
						}
                        AssDealCarDTO data = (AssDealCarDTO) result.getData();
                        ProductStatusLogVO productStatusLogVO = new ProductStatusLogVO();
                        productStatusLogVO.setPaySchId(assTrailCarDVO.getPaySchId());
                        productStatusLogVO.setPrjPrdId(Long.valueOf(prjPrdDtlId));
                        productStatusLogVO.setCurrentStatus(InterfaceConstants.PAY_STATUS_CD_S010602030101);
                        productStatusLogVO.setOpCode(InterfaceConstants.OP_CODE_OP0031);
                        productStatusLogVO.setProcessInstanceId(data.getProcId());
                        productStatusLogVO.setProcessInstanceCode(data.getProcNo());
                        this.assTrailCarMService.updateYQPrdStsCdByFlow(productStatusLogVO);
					}
				}
				//设置优车处置主表ID
				result.setData(id);
			}else{
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("发起优车处置申请流程失败！");
				BaseLogUtils.newLogger("新增优车处置信息主表数据失败").setKeys("id:" + id, "DATA:" + JSONObject.toJSONString(entity)).info();
			}
		}catch (BaseException ex) {
            BaseLogUtils.newLogger("新增优车处置信息主表数据失败").setThrowable(ex).setKeys("DATA:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		}catch (Exception ex) {
            BaseLogUtils.newLogger("新增优车处置信息主表数据失败").setThrowable(ex).setKeys("DATA:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		} finally {
		    // 若最后还在线程锁中，则释放锁
            if (lock) {
                userRedisService.releaseDistributedLock(key, requestId);
            }
        }
		return result;
	}
	
	/**
	 * 到优车处置流程附加信息页面
	 */
	@RequestMapping(value = "/toYCDealViewPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toYCDealViewPage(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		ModelAndView view = new ModelAndView("ass/assTrailCarM/assYCDealApplyView");
		// 优车处置id (ASS_DEAL_SELL表主键)
		String yc_deal_Id = request.getParameter("yc_deal_Id");
		// 流程实例ID
		String pInstId = request.getParameter("processInstanceId");
		if (StringUtils.isNotEmpty(pInstId)) {
			SysFlowSHQueryCondition flowQc = new SysFlowSHQueryCondition();
			flowQc.setpInstId(pInstId);
			flowQc.setWordsInTheTable(InterfaceConstants.ASS_FLOW_S_H_ASS);
			flowQc.setSysCd(CurrentThreadContext.getCurrentSysCd());
			flowQc.setStatus(BaseConstant.IS_YESNO_YES);
			flowQc.setBusTyp(FlowConstant.FLOW_MODEL_TYP_ASS_DEAL_YC);
			List<SysFlowSHDTO> flowSHDTOList = flowQueryApiService.searchFlowSHList(flowQc);
			if (CollectionUtils.isNotEmpty(flowSHDTOList)) {
				String pDefId = flowSHDTOList.get(0).getPDefId();
				if (StringUtils.isNotEmpty(pDefId)) {
					// FLOW_0000_019_001:9:aa22caa6-81f8-11e9-8ef3-005056902881
					String[] split = pDefId.split(":");
					String version = split[1];
					String boundary = PropertiesCacheUtils.getProperty("web.web.properties.ucar.cz.version.boundary");
					if (Integer.parseInt(version) > Integer.parseInt(boundary)) {
						// 重定向
						view.addObject("ycDealId", yc_deal_Id);
						view.setViewName("redirect:/ass/ucardeal/toUCarDealFlowPage.do");
						return view;
					}
				}
			}
		}

		//获取页面标识,flag为每个流程节点标识
		String flag = request.getParameter("flag");

		String isDetail = request.getParameter("isDetail");
		String sysCd = CurrentThreadContext.getCurrentSysCd();
		String orgCd = CurrentThreadContext.getCurrentOrgCd();

		//处置接收人类型
		List<KeyValueVO> buyerTypeList = this.assTrailCarMService.getKvList(InterfaceConstants.BUYER_TYPE_CD, sysCd, orgCd);
		view.addObject("buyerTypeList", buyerTypeList);
		//处置路径
		List<KeyValueVO> sellChannelList = this.assTrailCarMService.getKvList(InterfaceConstants.SELL_CHANNEL_CD, sysCd, orgCd);
		view.addObject("sellChannelList", sellChannelList);
		//数据类型
		List<KeyValueVO> dataTypeList = this.assTrailCarMService.getKvList(InterfaceConstants.DATA_TYPE_CD_SY, sysCd, orgCd);
		view.addObject("dataTypeList", dataTypeList);
		view.addObject("flag", flag);
		view.addObject("yc_deal_Id", yc_deal_Id);
		view.addObject("sysDate", DateUtils.formatDateToString(new Date(), DateUtils.YYYY_MM_DD));
		view.addObject("loginUsrNm", CurrentThreadContext.getCurrentUserName());

		AssDealSellVO sellVO = assDealSellService.selectById(Long.valueOf(yc_deal_Id));
		AssTrailCarDVO carDVO = this.assTrailCarDService.selectById(sellVO.getDetailId());
		String paySchId = null;
		if (null != carDVO && StringUtils.isNotEmpty(carDVO.getPaySchId())) {
		    // 该支付表是拖车明细中拿到的启用支付表
			paySchId = String.valueOf(carDVO.getPaySchId());
            List<PrjPrdPaySchMDTO> prjPrdPaySchMDTOS = this.prjPrdPaySchMService.searchTheSamePrdOtherPaySchMList(Long.valueOf(paySchId));
            for (PrjPrdPaySchMDTO prjPrdPaySchMDTO : prjPrdPaySchMDTOS) {
                if (PrjPrdPaySchMConstant.PAY_SCH_TYP_CD_WS.equals(prjPrdPaySchMDTO.getPaySchTypCd())) {
                    // 现在查出的我司支付表
                    String wsPaySchId = prjPrdPaySchMDTO.getId().toString();
                    view.addObject("wsPaySchId", wsPaySchId);
                    view.addObject("wsPaySchNo", prjPrdPaySchMDTO.getPaySchNo());
                }
            }
			view.addObject("paySchId", carDVO.getPaySchId());
		}
		view.addObject("isDetail", isDetail);

		//优车处置流程-查询绑定资金数据
		view = findBindFundData(request, view, paySchId, yc_deal_Id);

		return view;
	}
	
	/**
	 * 获取拖车交接单-附加信息
	 */
	@RequestMapping(value = "/getTransferInfo.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getTransferInfo(HttpServletRequest request, HttpServletResponse response) {
		//获取页面参数
		String tcDetailId = request.getParameter("tcDetailId");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(tcDetailId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			AssTrailCarHvVO vo = this.assTrailCarDService.selectTransferInfoById(Long.valueOf(tcDetailId));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				return result;
			}
			//返回一条数据
			result.setData(vo);
		}catch(BaseException ex) {
			BaseLogUtils.newLogger("获取拖车交接单数据失败").setThrowable(ex).setKeys("detailId:" + tcDetailId).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
			throw ex;
		}catch(Exception ex) {
            BaseLogUtils.newLogger("获取拖车交接单数据失败").setThrowable(ex).setKeys("detailId:" + tcDetailId).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		}
		return result;
	}
	
	/**
	 * 修改出入库备注
	 */
	@RequestMapping(value = "/modifyEORem.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modifyEORem(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String tcDetailId = request.getParameter("tcDetailId");
		String crflag = request.getParameter("crflag");//出入库标识
		String entryOutRem = request.getParameter("entryOutRem");//备注
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(tcDetailId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		AssTrailCarDVO entity = null;
		try {
			entity = new AssTrailCarDVO();
			entity.setId(Long.valueOf(tcDetailId));
			//判断是出库,还是入库
			if(StringUtils.isNotEmpty(crflag)){
				if("entry".equals(crflag)){//入库备注
					entity.setEnterRem(entryOutRem);
				}else if("out".equals(crflag)){//出库备注
					entity.setOutRem(entryOutRem);
				}
			}
			//设置主表实体属性
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setMdfTm(new Date());
			boolean success = this.assTrailCarDService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.newLogger("修改出入库备注失败").setKeys("detailId:" + tcDetailId, "DATA:" + JSON.toJSONString(entity)).info();
			}
		}catch (BaseException ex) {
            BaseLogUtils.newLogger("修改出入库备注失败").setKeys("detailId:" + tcDetailId, "DATA:" + JSON.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		}catch (Exception ex) {
            BaseLogUtils.newLogger("修改出入库备注失败").setKeys("detailId:" + tcDetailId, "DATA:" + JSON.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		}
		return result;
	}
	
	/**
	 * 获取处置申请主表信息-JL
	 */
	@RequestMapping(value = "/getDealInfoById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getDealInfoById(HttpServletRequest request, HttpServletResponse response) {
		//获取页面参数
		String dealId = request.getParameter("dealId");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(dealId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			AssDealSellVO vo = this.assDealSellService.selectById(Long.valueOf(dealId));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				return result;
			}
			//返回一条数据
			result.setData(vo);
		}catch(BaseException ex) {
			BaseLogUtils.newLogger("获取处置主表数据失败").setThrowable(ex).setKeys("dealId:" + dealId).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
			throw ex;
		}catch(Exception ex) {
            BaseLogUtils.newLogger("获取处置主表数据失败").setThrowable(ex).setKeys("dealId:" + dealId).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		}
		return result;
	}
	
	/**
	 * 新增或更新处置表信息
	 */
	@RequestMapping(value = "/updateYCDealInfo.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object updateYCDealInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		//获取页面参数
		String dataId = request.getParameter("dataId");
		String pNo = "";//流程号
		String paySchNO = "";//支付表号
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(dataId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}else{
			//根据业务主键查询流程号和支付表号
			AssTrailCarDInfVO infVo = this.assTrailCarDInfService.selectPNoPaySchNoByDataId(Long.valueOf(dataId));
			if(infVo != null){
				pNo = infVo.getPNo();
				paySchNO = infVo.getPaySchNo();
			}
		}
		// kfc add start 170905
		String goFlag = request.getParameter("goFlag");
		if (null != goFlag && !("").equals(goFlag) && (goFlag.equals("4") || goFlag == "4")) {//拖车
			String tcDetailId = request.getParameter("tcDetailId");
			AssTrailCarDQueryCondition con = new AssTrailCarDQueryCondition();
			con.setMasterId(Long.valueOf(dataId));
			List<AssTrailCarDVO> vo = this.assTrailCarDService.searchDetailList(con);
			if (vo != null && vo.size() > 0) {
				if (!"2".equals(vo.get(0).getBackedFlagCd())&&!"3".equals(vo.get(0).getBackedFlagCd())) {
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("请先保存拖回标记状态");
					return result;
				}
			}else{
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				return result;
			}
		}
		// kfc add end 170905
		AssDealRecAmtVO vo = null;
		try {
			String assDealRecAmt_id = request.getParameter("assDealRecAmt_id");
			String payerAccNm = request.getParameter("payerAccNm");//付款方名称
			String receivedTm = request.getParameter("fReceivedTm");//付款时间
			String receivedAmt = request.getParameter("fReceivedAmt");//到账金额
			String payerBankNm =  request.getParameter("payerBankNm");//银行信息
			String payerAccNo = request.getParameter("payerAccNo");//账号信息
			String payAmt = request.getParameter("payAmt");//付款金额
			String payTm = request.getParameter("payTm");//付款时间
			String dataTypeCd = request.getParameter("dataTypeCd");

			String useAmt = request.getParameter("useAmt");//使用金额
            if (!ValidateUtil.validateIsAmt(useAmt) || !ValidateUtil.validateIsAmt(receivedAmt) || !ValidateUtil.validateIsAmt(payAmt)) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("金额格式输入有误，请修改后重新保存");
                return result;
            }
			vo = new AssDealRecAmtVO();
			vo.setRemark("流程号：" + pNo + ";支付表号：" + paySchNO);
			vo.setCurrentUserId(CurrentThreadContext.getCurrentUserId());
			vo.setCurrentUserName(CurrentThreadContext.getCurrentUserName());
			vo.setPayerAccNm(payerAccNm);//付款方账户名称
			vo.setPayerAccNo(payerAccNo);//付款方银行账号
			vo.setPayerBankNm(payerBankNm);//付款方开户银行
			vo.setDataId(Long.valueOf(dataId));
			vo.setDataTypeCd(dataTypeCd);//数据类型
			//使用金额
			if(StringUtils.isNotEmpty(useAmt)){//元转分
				vo.setUseAmt(DecimalUtils.convertYuanToFen(Double.valueOf(useAmt)));
			}
			if(StringUtils.isNotEmpty(receivedAmt)){//元转分
				vo.setReceivedAmt(DecimalUtils.convertYuanToFen(Double.valueOf(receivedAmt)));
			}
			if(StringUtils.isNotEmpty(receivedTm)){//到账时间
				vo.setReceivedTm(DateUtils.formatStringToDate(receivedTm, DateUtils.YYYY_MM_DD));
			}
			if(StringUtils.isNotEmpty(payAmt)){//元转分
				vo.setPayAmt(DecimalUtils.convertYuanToFen(Double.valueOf(payAmt)));
			}
			if(StringUtils.isNotEmpty(payTm)){//付款时间
				vo.setPayTm(DateUtils.formatStringToDate(payTm, DateUtils.YYYY_MM_DD));
			}
			if (StringUtils.isNotEmpty(assDealRecAmt_id)) {//更新
				vo.setId(Long.valueOf(assDealRecAmt_id));
				vo.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
				vo.setMdfTm(new Date());
				boolean success =  this.assDealRecAmtService.modify(vo);
				if(!success){
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
					BaseLogUtils.newLogger("修改处置收款表信息失败").setKeys("id:" + assDealRecAmt_id, "DATA:" + JSONObject.toJSONString(vo)).info();
				}
			}else{
				vo.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
				vo.setCrtTm(new Date());
				vo.setIsDel(BaseConstant.IS_YESNO_NO);
				Long id = this.assDealRecAmtService.add(vo);
				result.setInfo(SysLogConstant.LOG_CMM_ADD_SUCC);
				if(null == id){
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo(SysLogConstant.LOG_CMM_ADD_FAIL);
                    BaseLogUtils.newLogger("新增处置收款表信息失败").setKeys("data_id:" + dataId, "DATA:" + JSONObject.toJSONString(vo)).info();
				}else{
					result.setData(id);
				}
			}
			
		}catch (BaseException ex) {
			BaseLogUtils.newLogger("新增或更新处置收款表信息失败").setThrowable(ex).setKeys(JSONObject.toJSONString(vo)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
			throw ex;
		}catch (Exception ex) {
            BaseLogUtils.newLogger("新增或更新处置收款表信息失败").setThrowable(ex).setKeys(JSONObject.toJSONString(vo)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		}
		return result;
	}
	
	/**
	 * 修改处置主表信息
	 */
	@RequestMapping(value = "/modifyDealInfo.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modifyDealInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		//获取页面参数
		String dealId = request.getParameter("deal_Id");
		String buyerTypeCd = request.getParameter("buyerTypeCd");
		String sellAmt = request.getParameter("sellAmt");
		String sellChannelCd = request.getParameter("sellChannelCd");
		String buyerNm = request.getParameter("buyerNm");
		String buyerCd = request.getParameter("buyerCd");
		String buyerTel = request.getParameter("buyerTel");
		String buyerCompanyNm = request.getParameter("buyerCompanyNm");
		String buyerCompanyContact = request.getParameter("buyerCompanyContact");
		String buyerCompanyTel = request.getParameter("buyerCompanyTel");
		String buyerCompanyCode = request.getParameter("buyerCompanyCode");
		String sellDesc = request.getParameter("sellDesc");
		String payeeAccNm = request.getParameter("payeeAccNm");
		String payeeBankNm = request.getParameter("payeeBankNm");
		String payeeAccNo = request.getParameter("payeeAccNo");
		String isReceived = request.getParameter("isReceived");
		String receivedAmt = request.getParameter("receivedAmt");
		String receivedTm = request.getParameter("receivedTm");
		String pickCarNm = request.getParameter("pickCarNm");
		String pickCarTel = request.getParameter("pickCarTel");
		String pickCarCd = request.getParameter("pickCarCd");
		String sellEstiAmt = request.getParameter("sellEstiAmt");//处置评估价
		String sellEstiDt = request.getParameter("stDt");//处置评估时间
		String flag = request.getParameter("flag");//流程标识
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(dealId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		AssDealSellVO entity = null;
		try {
			entity = new AssDealSellVO();
			entity.setId(Long.valueOf(dealId));
			//判断是发起人节点,还是通知打款节点,还是财务确认到账节点
			if(StringUtils.isNotEmpty(flag)){//流程标识
				if("7".equals(flag) || "9".equals(flag) || "4".equals(flag)){//付款信息
					entity.setPayeeAccNm(payeeAccNm);
					entity.setPayeeBankNm(payeeBankNm);
					entity.setPayeeAccNo(payeeAccNo);
					entity.setPickCarNm(pickCarNm);
					entity.setPickCarTel(pickCarTel);
					entity.setPickCarCd(pickCarCd);
					/*if(null != sellEstiAmt){//元转分
						entity.setSellEstiAmt(DecimalUtils.convertYuanToFen(Double.valueOf(sellEstiAmt)));//处置评估价
					}
					if(null != sellEstiDt){
						entity.setSellEstiDt(DateUtils.formatStringToDate(sellEstiDt, DateUtils.YYYY_MM_DD));//处置评估时间
					}*/
					if(StringUtils.isNotEmpty(sellEstiAmt)){
						entity.setSellEstiAmt(DecimalUtils.convertYuanToFen(Double.valueOf(sellEstiAmt)));//处置评估价
					}
					if(StringUtils.isNotEmpty(sellEstiDt)){
						entity.setSellEstiDt(DateUtils.formatStringToDate(sellEstiDt, DateUtils.YYYY_MM_DD));//处置评估时间
					}
				}else if("2".equals(flag)){//基本信息
					if(StringUtils.isNotEmpty(sellAmt)){//元转分
						entity.setSellAmt(DecimalUtils.convertYuanToFen(Double.valueOf(sellAmt)));
					}
					entity.setBuyerTypeCd(buyerTypeCd);
					entity.setSellChannelCd(sellChannelCd);
					entity.setBuyerNm(buyerNm);
					entity.setBuyerCd(buyerCd);
					entity.setBuyerTel(buyerTel);
					entity.setBuyerCompanyNm(buyerCompanyNm);
					entity.setBuyerCompanyContact(buyerCompanyContact);
					entity.setBuyerCompanyTel(buyerCompanyTel);
					entity.setBuyerCompanyCode(buyerCompanyCode);
					entity.setSellDesc(sellDesc);
					if(StringUtils.isNotEmpty(sellEstiAmt)){
						entity.setSellEstiAmt(DecimalUtils.convertYuanToFen(Double.valueOf(sellEstiAmt)));//处置评估价
					}
					if(StringUtils.isNotEmpty(sellEstiDt)){
						entity.setSellEstiDt(DateUtils.formatStringToDate(sellEstiDt, DateUtils.YYYY_MM_DD));//处置评估时间
					}
				}else if("8".equals(flag) || "6".equals(flag)){//实际付款信息
					if(StringUtils.isNotEmpty(isReceived)){//是否到账
						entity.setIsReceived(Integer.parseInt(isReceived));
					}
					if(StringUtils.isNotEmpty(receivedAmt)){//元转分
						entity.setReceivedAmt(DecimalUtils.convertYuanToFen(Double.valueOf(receivedAmt)));
					}
					if(StringUtils.isNotEmpty(receivedTm)){
						entity.setReceivedTm(DateUtils.formatStringToDate(receivedTm, DateUtils.YYYY_MM_DD));
					}
				}
			}
			//设置主表实体属性
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setMdfTm(new Date());
			boolean success = this.assDealSellService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.newLogger("修改处置主表信息失败").setKeys("id:" + dealId, "DATA:" + JSONObject.toJSONString(entity)).info();
			}
		}catch (BaseException ex) {
            BaseLogUtils.newLogger("修改处置主表信息失败").setThrowable(ex).setKeys("id:" + dealId, "DATA:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		}catch (Exception ex) {
            BaseLogUtils.newLogger("修改处置主表信息失败").setThrowable(ex).setKeys("id:" + dealId, "DATA:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		}
		return result;
	}
	 /**
     * 初始化列表--提报费用 kfc
     * 
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initCostList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initCostList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(currentPage)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        AssDealCarCostQueryCondition qc = new AssDealCarCostQueryCondition();
        //设置查询条件？
        String CAR_ID = request.getParameter("CAR_ID");//优车ID
        if (StringUtils.isNotEmpty(CAR_ID)) {
            qc.setCarId(Long.valueOf(CAR_ID));
        }
        qc.setIsDel(BaseConstant.IS_YESNO_NO);
        page.setCondition(qc);

        Pager pager = this.assDealCarCostService.findAssDealCarCostListByPage(page);
        List<AssDealCarCostVO> list = (List<AssDealCarCostVO>) pager.getResultList();
        ListPageVO<AssDealCarCostVO> listPage = new ListPageVO<AssDealCarCostVO>(list, pager.getTotalCount());
        return listPage;
    }
    /**
     * 到新增页面(处置-转优车费用信息表) kfc
     */
    @RequestMapping(value = "/toAddCostPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toAddCostPage(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mav = new ModelAndView("ass/assTrailCarD/assCostInfoAdd");
        List<SysDictionaryDTO> costTypeCdList = sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd() ,InterfaceConstants.COST_TYPE_CD);
        mav.addObject("costTypeCdList", costTypeCdList);
        mav.addObject("carId", request.getParameter("carId"));
        return mav;
    }
    
    /**
     * 新增(处置-转优车费用信息表) kfc
     */
    @RequestMapping(value = "/addCarCost.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object addCarCost(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        AssDealCarCostVO entity = null;//获取参数
        String carId = request.getParameter("carId");
        String costTypeCd = request.getParameter("costTypeCd");
        String costAmt = request.getParameter("costAmt");
        String costRem = request.getParameter("costRem");
		String loanTypCd = request.getParameter("loanTypCd");
		String payTypCd = request.getParameter("payTypCd");
		String loanApplyAmt = request.getParameter("loanApplyAmt");
		String sysEmpBankId = request.getParameter("sysEmpBankId");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		if(StringUtils.isEmpty(carId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		if(StringUtils.isEmpty(costAmt)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_ADD_FAIL);
			return result;
		}
		entity = new AssDealCarCostVO();
		entity.setCarId(Long.valueOf(carId));
		if (StringUtils.isNotEmpty(costAmt)) {
			entity.setCostAmt(DecimalUtils.convertYuanToFen(Double.valueOf(costAmt)));
		}
		entity.setCostRem(costRem);
		entity.setCostTypeCd(costTypeCd);
		entity.setLoanTypCd(loanTypCd);
		entity.setPayTypCd(payTypCd);
		if (StringUtils.isNotEmpty(loanApplyAmt)) {
			entity.setLoanApplyAmt(DecimalUtils.convertYuanToFen(Double.valueOf(loanApplyAmt)));
		}
		if (StringUtils.isNotEmpty(sysEmpBankId)) {
			entity.setSysEmpBankId(Long.parseLong(sysEmpBankId));
		}
		entity.setIsDel(BaseConstant.IS_YESNO_NO);
		entity.setCrtTm(new Date());
		entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
        try {
            Long id = this.assDealCarCostService.saveAssDealCarCost(entity);
            result.setData(id);
        } catch (BaseException ex) {
            BaseLogUtils.newLogger("新增处置-转优车费用信息表数据失败").setThrowable(ex).setKeys("DATA:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
        } catch (Exception ex) {
            BaseLogUtils.newLogger("新增处置-转优车费用信息表数据失败").setThrowable(ex).setKeys("DATA:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
        }
        return result;
    }

    /**
     * 到修改页面(处置-转优车费用信息表) kfc
     */
    @RequestMapping(value = "/toUpdateCostPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toUpdateCostPage(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mav = new ModelAndView("ass/assTrailCarD/assCostInfoUpdate");
        String id = request.getParameter("id");
        AssDealCarCostVO vo = this.assDealCarCostService.selectById(Long.valueOf(id));
        List<SysDictionaryDTO> costTypeCdList = sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd() ,InterfaceConstants.COST_TYPE_CD);
        mav.addObject("costTypeCdList", costTypeCdList);
        mav.addObject("vo", vo);
        return mav;
    }
    /**
     * 修改(处置-转优车费用信息表) kfc
     */
    @RequestMapping(value = "/updateCarCost.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object updateCarCost(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        AssDealCarCostVO entity = null;//获取参数
        String carId = request.getParameter("carId");
        String id = request.getParameter("id");
        String costTypeCd = request.getParameter("costTypeCd");
        String costAmt = request.getParameter("costAmt");
        String costRem = request.getParameter("costRem");
        String loanTypCd = request.getParameter("loanTypCd");
        String payTypCd = request.getParameter("payTypCd");
        String loanApplyAmt = request.getParameter("loanApplyAmt");
        String sysEmpBankId = request.getParameter("sysEmpBankId");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		if(StringUtils.isEmpty(costAmt)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
			return result;
		}
		entity = new AssDealCarCostVO();
		entity.setId(Long.valueOf(id));
		entity.setCarId(Long.valueOf(carId));
		if (StringUtils.isNotEmpty(costAmt)) {
			entity.setCostAmt(DecimalUtils.convertYuanToFen(Double.valueOf(costAmt)));
		}
		//entity.setCostAmt(Long.valueOf(costAmt));
		entity.setCostRem(costRem);
		entity.setCostTypeCd(costTypeCd);
		entity.setLoanTypCd(loanTypCd);
		entity.setPayTypCd(payTypCd);
		if (StringUtils.isNotEmpty(loanApplyAmt)) {
			entity.setLoanApplyAmt(DecimalUtils.convertYuanToFen(Double.valueOf(loanApplyAmt)));
		}
		if (StringUtils.isNotEmpty(sysEmpBankId)) {
			entity.setSysEmpBankId(Long.parseLong(sysEmpBankId));
		}
		entity.setMdfTm(new Date());
		entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
        try {
            boolean success = this.assDealCarCostService.modify(entity);
            if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.newLogger("修改ASS_DEAL_CAR_COST信息失败").setKeys("id:" + id, "DATA:" + JSONObject.toJSONString(entity)).info();
			}
        } catch (BaseException ex) {
            BaseLogUtils.newLogger("修改ASS_DEAL_CAR_COST信息失败").setThrowable(ex).setKeys("id:" + id, "DATA:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
        } catch (Exception ex) {
            BaseLogUtils.newLogger("修改ASS_DEAL_CAR_COST信息失败").setThrowable(ex).setKeys("id:" + id, "DATA:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
        }
        return result;
    }

    /**
     * 删除(处置-转优车费用信息表) kfc
     */
    @RequestMapping(value = "/deleteCarCost.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO deleteCarCost(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            return result;
        }

        try {
            boolean success = this.assDealCarCostService.removeById(Long.valueOf(id));
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
                BaseLogUtils.newLogger("删除ASS_DEAL_CAR_COST数据失败").setKeys("id:" + id).info();
            }
        } catch (BaseException ex) {
            BaseLogUtils.newLogger("删除ASS_DEAL_CAR_COST数据失败").setThrowable(ex).setKeys("id:" + id).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
        } catch (Exception ex) {
            BaseLogUtils.newLogger("删除ASS_DEAL_CAR_COST数据失败").setThrowable(ex).setKeys("id:" + id).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
        }
        return result;
    }
	
	/**
	 * 获取赎回申请主表信息-JL
	 */
	@RequestMapping(value = "/getRedeemInfoById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getRedeemInfoById(HttpServletRequest request, HttpServletResponse response) {
		//获取页面参数
		String redeemId = request.getParameter("redeemId");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(redeemId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			AssDealRedeemVO vo = this.assDealRedeemService.selectById(Long.valueOf(redeemId));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				return result;
			}else{
				//查询赎回流程创建者-真实姓名
				SysUsrVO usrVo = null;
				String sysCd = CurrentThreadContext.getCurrentSysCd();
				usrVo = this.sysUsrService.selectById(vo.getCrtUsrId(), sysCd);
				vo.setCrtUsrRlNm(usrVo.getRefRlNm());
			}
			//返回一条数据
			result.setData(vo);
		}catch(BaseException ex) {
			BaseLogUtils.newLogger("获取赎回主表数据失败").setThrowable(ex).setKeys("redeemId:" + redeemId).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
			throw ex;
		}catch(Exception ex) {
            BaseLogUtils.newLogger("获取赎回主表数据失败").setThrowable(ex).setKeys("redeemId:" + redeemId).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		}
		return result;
	}
	
	/**
	 * 修改赎回主表信息
	 */
	@RequestMapping(value = "/modifyRedeemInfo.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modifyRedeemInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		//获取页面参数
		String redeemId = request.getParameter("redeem_Id");
		String cstNm = request.getParameter("cstNm");
		String redeemTypeCd = request.getParameter("redeemTypeCd");
		String redeemAddr = request.getParameter("redeemAddr");
		String redeemTm = request.getParameter("redeemTm");
		String isOnline = request.getParameter("isOnline");
		String overdueAmt = request.getParameter("overdueAmt");
		String interestAmt = request.getParameter("interestAmt");
		String depositPct = request.getParameter("depositPct");
		String amtTypeCd = request.getParameter("amtTypeCd");
		String depositAmt = request.getParameter("depositAmt");
		String depositBaseAmt = request.getParameter("depositBaseAmt");
		String receivableAmt = request.getParameter("receivableAmt");
		String actPayAmt = request.getParameter("actPayAmt");
		String actPayTm = request.getParameter("actPayTm");
		String redeemAmt = request.getParameter("redeemAmt");
		String redeemDesc = request.getParameter("redeemDesc");
		String payeeAccNm = request.getParameter("payeeAccNm");
		String payeeBankNm = request.getParameter("payeeBankNm");
		String payeeAccNo = request.getParameter("payeeAccNo");
		String pickCarNm = request.getParameter("pickCarNm");
		String pickCarTel = request.getParameter("pickCarTel");
		String pickCarCd = request.getParameter("pickCarCd");
		String flag = request.getParameter("flag");//流程标识
		//截止到财务到账节点逾期等信息
		String actOverdueAmt = request.getParameter("actOverdueAmt");
		String actInterestAmt = request.getParameter("actInterestAmt");
		String actRedeemAmt = request.getParameter("actRedeemAmt");

		String tcDetailId = request.getParameter("tcDetailId");
		// gps信息
		String gps1 = request.getParameter("gps1");
        String gps2 = request.getParameter("gps2");
        String gps3 = request.getParameter("gps3");
        // 安装人
        String installer = request.getParameter("installer");
        // 安装时间
        String installDt = request.getParameter("installDt");
        // 备注
        String gpsRem = request.getParameter("gpsRem");
        // 支付表id
        String paySchId = request.getParameter("paySchId");

		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(redeemId) || StringUtils.isEmpty(paySchId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		AssDealRedeemVO entity = null;
		try {
			entity = new AssDealRedeemVO();
			entity.setId(Long.valueOf(redeemId));
			//判断是发起人节点,还是通知打款节点,还是财务确认到账节点
			if(StringUtils.isNotEmpty(flag)){//流程标识
				if("5".equals(flag) || "7".equals(flag)){//通知打款
					if("5".equals(flag)){//付款信息
						entity.setPayeeAccNm(payeeAccNm);
						entity.setPayeeBankNm(payeeBankNm);
						entity.setPayeeAccNo(payeeAccNo);
					}
					//提车人信息
					entity.setPickCarNm(pickCarNm);
					entity.setPickCarTel(pickCarTel);
					entity.setPickCarCd(pickCarCd);
				}else if("1".equals(flag) || "2".equals(flag) || "6".equals(flag)){//基本信息-风险保证金1
					if("1".equals(flag) || "2".equals(flag)){//发起人-财务核算
						if("1".equals(flag)){
							if(StringUtils.isNotEmpty(redeemTm)){
								entity.setRedeemTm(DateUtils.formatStringToDate(redeemTm, DateUtils.YYYY_MM_DD));
							}
							entity.setCstNm(cstNm);
							entity.setRedeemTypeCd(redeemTypeCd);
							entity.setRedeemAddr(redeemAddr);
						}else{
							if(StringUtils.isNotEmpty(receivableAmt)){//应收金额
								entity.setReceivableAmt(DecimalUtils.convertYuanToFen(Double.valueOf(receivableAmt)));
							}
						}
						if(StringUtils.isNotEmpty(overdueAmt)){//赎回逾期租金
							entity.setOverdueAmt(DecimalUtils.convertYuanToFen(Double.valueOf(overdueAmt)));
						}
						if(StringUtils.isNotEmpty(interestAmt)){//赎回罚息
							entity.setInterestAmt(DecimalUtils.convertYuanToFen(Double.valueOf(interestAmt)));
						}
						if(StringUtils.isNotEmpty(redeemAmt)){//赎回金额
							entity.setRedeemAmt(DecimalUtils.convertYuanToFen(Double.valueOf(redeemAmt)));
						}
						entity.setRedeemDesc(redeemDesc);//赎回说明
					}else if("6".equals(flag)){//财务确认到账-实际付款信息
						if(StringUtils.isNotEmpty(actPayAmt)){//元转分
							entity.setActPayAmt(DecimalUtils.convertYuanToFen(Double.valueOf(actPayAmt)));
						}
						if(StringUtils.isNotEmpty(actPayTm)){
							entity.setActPayTm(DateUtils.formatStringToDate(actPayTm, DateUtils.YYYY_MM_DD));
						}
						if(StringUtils.isNotEmpty(actOverdueAmt)){//元转分-实际赎回逾期租金
							entity.setActOverdueAmt(DecimalUtils.convertYuanToFen(Double.valueOf(actOverdueAmt)));
						}
						if(StringUtils.isNotEmpty(actInterestAmt)){//元转分-实际赎回罚息
							entity.setActInterestAmt(DecimalUtils.convertYuanToFen(Double.valueOf(actInterestAmt)));
						}
						if(StringUtils.isNotEmpty(actRedeemAmt)){//元转分-实际赎回金额
							entity.setActRedeemAmt(DecimalUtils.convertYuanToFen(Double.valueOf(actRedeemAmt)));
						}
					}
					//三个节点都可以修改的信息
					if(StringUtils.isNotEmpty(depositPct)){//赎回保证金比例
						entity.setDepositPct(Double.parseDouble(depositPct));;
					}
					if(StringUtils.isNotEmpty(depositAmt)){//赎回保证金
						entity.setDepositAmt(DecimalUtils.convertYuanToFen(Double.valueOf(depositAmt)));
					}
					if(StringUtils.isNotEmpty(depositBaseAmt)){//赎回保证金基数
						entity.setDepositBaseAmt(DecimalUtils.convertYuanToFen(Double.valueOf(depositBaseAmt)));
					}
					entity.setAmtTypeCd(amtTypeCd);//赎回保证金计算基数类型
				}
				if ("2".equals(flag) || "6".equals(flag)) {
				    // 财务核算赎回金额&财务确认到账金额时间
                    // 只有赎回结清才重新计算IRR和结清优惠金额1
                    if (InterfaceConstants.REDEEM_TYPE_CD_1.equals(redeemTypeCd)) {
                        AssDealRedeemVO assDealRedeemVO = this.assDealRedeemService.selectById(Long.valueOf(redeemId));
                        if (null == assDealRedeemVO.getCrtTm()) {
                            throw new BaseException("无法获得拖车赎回发起时间");
                        }
                        // 若财务修改赎回金额则重新核算IRR和结清优惠金额1
                        Map<String, Double> calcStlCstIRRAndDiscount = this.assDealRedeemService.getCalcStlCstIRRAndDiscount(Long.valueOf(paySchId), DecimalUtils.convertYuanToFen(Double.valueOf(redeemAmt)), assDealRedeemVO.getCrtTm());
                        JSONObject json = new JSONObject();
                        if (CollectionUtils.isMapNotEmpty(calcStlCstIRRAndDiscount)) {
                            Double cstStlIrr = calcStlCstIRRAndDiscount.get("irr");
                            Double discountAmt = calcStlCstIRRAndDiscount.get("discountAmtIRR");
                            boolean success = this.assDealRedeemService.saveStlCstIrrAndDiscountAmt(Long.valueOf(redeemId), Long.valueOf(paySchId), cstStlIrr, discountAmt, CurrentThreadContext.getCurrentUserId());
                            if (false == success) {
                                throw new BaseException("保存对客结清IRR和结清优惠金额1异常！");
                            }
                            // 返回的irr是小数，结清优惠金额1金额是分
                            json.put("cstStlIrr", cstStlIrr);
                            json.put("discountAmt", discountAmt / 100);
                        } else {
                            json.put("cstStlIrr", 0);
                            json.put("discountAmt", 0);
                        }
                        result.setData(json);
                    }
				}
				if("1".equals(flag) || "11".equals(flag)){//发起人-商助
                    //修改GPS在线状态
					if(StringUtils.isNotEmpty(isOnline)){
						entity.setIsOnline(Integer.parseInt(isOnline));
					}
				}
				if ("11".equals(flag) && InterfaceConstants.REDEEM_TYPE_CD_2.equals(redeemTypeCd)) {
                    // 商助审核gps节点（移动后）
                    if (StringUtils.isEmpty(tcDetailId)) {
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
                        return result;
                    }
                    AssTrailCarDVO assTrailCarDVO = this.assTrailCarDService.selectById(Long.valueOf(tcDetailId));
                    Long prjPrdDtlId = assTrailCarDVO.getPrjPrdDtlId();
                    if (StringUtils.isNotEmpty(prjPrdDtlId)) {
                        // gps卡号
                        List<String> gpsNos = new ArrayList<>();
                        if (StringUtils.isNotEmpty(gps1)) {
                            gpsNos.add(gps1);
                        }
                        if (StringUtils.isNotEmpty(gps2)) {
                            gpsNos.add(gps2);
                        }
                        if (StringUtils.isNotEmpty(gps3)) {
                            gpsNos.add(gps3);
                        }
                        if (CollectionUtils.isNotEmpty(gpsNos)) {
                            Long cstMgrId = 0L;
                            if (StringUtils.isNotEmpty(assTrailCarDVO.getPrjId())) {
                                PrjBscInfoVO prjBscInfoVO = prjBscInfoService.selectById(assTrailCarDVO.getPrjId());
                                cstMgrId = prjBscInfoVO.getCstMgrId();
                            }
                            if (cstMgrId.equals(0L)) {
                                throw new BaseException("未查到该项目客户经理ID");
                            }
                            DataResultVO resultVO = assDealRedeemService.validateGPS(gpsNos, prjPrdDtlId, cstMgrId);
                            if (null != resultVO) {
                                if (BaseConstant.IS_YESNO_NO == resultVO.getSuccess()) {
                                    return resultVO;
                                } else if (2 == resultVO.getSuccess()) {
                                    result.setSuccess(resultVO.getSuccess());
                                    result.setInfo(resultVO.getInfo());
                                    result.setData(resultVO.getData());
                                } else if (BaseConstant.IS_YESNO_YES == resultVO.getSuccess()) {
                                    result.setData(resultVO.getData());
                                }
                            }
                        }
                    }
                }
			}
			//设置主表实体属性
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setMdfTm(new Date());
			boolean success = this.assDealRedeemService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.newLogger("修改赎回主表信息失败").setKeys("id:" + redeemId, "DATA:" + JSONObject.toJSONString(entity)).info();
			}
		}catch (BaseException ex) {
            BaseLogUtils.newLogger("修改赎回主表信息失败").setThrowable(ex).setKeys("id:" + redeemId, "DATA:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		}catch (Exception ex) {
            BaseLogUtils.newLogger("修改赎回主表信息失败").setThrowable(ex).setKeys("id:" + redeemId, "DATA:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		}
		return result;
	}

    /**
     * 保存GPS信息
     * @param request
     * @throws BaseException
     */
    @RequestMapping(value = "/saveGPSInfoOfNewRules.do", method = { RequestMethod.POST })
    @ResponseBody
    public Object saveGPSInfoOfNewRules(HttpServletRequest request) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
        // gps信息
        String gps1 = request.getParameter("gps1");
        String gps2 = request.getParameter("gps2");
        String gps3 = request.getParameter("gps3");
        // 安装人
        String installer = request.getParameter("installer");
        // 安装时间
        String installDt = request.getParameter("installDt");
        // 备注
        String gpsRem = request.getParameter("gpsRem");
        String tcDetailId = request.getParameter("tcDetailId");

        // 领用人工号1
        String receiveName1 = request.getParameter("receiveName1");
        // 领用人真实姓名1
        String receiveRealName1 = request.getParameter("receiveRealName1");
        // 设备类型1
        String gpsDeviceType1 = request.getParameter("gpsDeviceType1");
        // 领用人工号2
        String receiveName2 = request.getParameter("receiveName2");
        // 领用人真实姓名2
        String receiveRealName2 = request.getParameter("receiveRealName2");
        // 设备类型2
        String gpsDeviceType2 = request.getParameter("gpsDeviceType2");
        // 领用人工号3
        String receiveName3 = request.getParameter("receiveName3");
        // 领用人真实姓名3
        String receiveRealName3 = request.getParameter("receiveRealName3");
        // 设备类型3
        String gpsDeviceType3 = request.getParameter("gpsDeviceType3");

        // gps卡号
        List<String> gpsNums = new LinkedList<String>();
        gpsNums.add(gps1);
        gpsNums.add(gps2);
        gpsNums.add(gps3);
        List<PrjPrdDtlGpsVO> voList = new ArrayList<>();
        try {
            AssTrailCarDVO assTrailCarDVO = this.assTrailCarDService.selectById(Long.valueOf(tcDetailId));
            Long prjPrdDtlId = assTrailCarDVO.getPrjPrdDtlId();
            for (int i = 0; i < gpsNums.size(); i++) {
                String gpsNum = gpsNums.get(i);
                DataResultDTO dto = this.prjPrdVehInfoService.getGPSInfo(gpsNum);
                JSONObject obj = (JSONObject) JSONObject.toJSON(dto.getData());
                List<PrjPrdDtlGpsVO> gpsVOList = this.prjPrdDtlGpsService.gpsIsExist(prjPrdDtlId, i + 1);
                PrjPrdDtlGpsVO newVo = new PrjPrdDtlGpsVO();
                newVo.setPrjDtlId(prjPrdDtlId);
                newVo.setGpsCardNo(gpsNum);
                newVo.setSerialNo(i + 1);
                newVo.setIsDel(0);//是否删除（1：是，0：否）
                newVo.setInstaller(installer);
                newVo.setInstallDt(DateUtils.formatStringToDate(installDt, DateUtils.YYYY_MM_DD));
                newVo.setGpsRem(gpsRem);
                if (i == 0) {
                    newVo.setReceiveName(receiveName1);
                    newVo.setReceiveRealName(receiveRealName1);
                    newVo.setGpsDeviceType(gpsDeviceType1);
                } else if (i == 1) {
                    newVo.setReceiveName(receiveName2);
                    newVo.setReceiveRealName(receiveRealName2);
                    newVo.setGpsDeviceType(gpsDeviceType2);
                } else if (i == 2) {
                    newVo.setReceiveName(receiveName3);
                    newVo.setReceiveRealName(receiveRealName3);
                    newVo.setGpsDeviceType(gpsDeviceType3);
                }
                if (null != obj) {
                    newVo.setUseTypCd(obj.getString("useType"));// 领用状态 0.未领用 1.已领用
                    newVo.setGpsStsCd(obj.getString("isExist"));// GPS平台状态 0.参数错误 1.设备不存在 2.设备正常 3.设备无位置信息,4：设备未入库
                    newVo.setGpsAddrInfo(obj.getString("address"));// 中文位置信息
                    newVo.setLat(obj.getString("lat"));// 纬度（保留两位小数）
                    newVo.setLng(obj.getString("lng"));// 经度（保留两位小数）
                    newVo.setOnlineType(obj.getString("onlineType"));
                }
                newVo.setCrtTm(new Date());// 创建时间
                newVo.setCrtUsrId(CurrentThreadContext.getCurrentUserId());// 创建人
                if (gpsVOList != null && gpsVOList.size() > 0) {
                    PrjPrdDtlGpsVO vo = gpsVOList.get(0);
                    Long applyId = vo.getApplyId();//申请ID
                    String audStsCd = vo.getAudStsCd();//审核状态
                    newVo.setAudStsCd(audStsCd);// 审核状态 0.未审核 1.审核中 2.已审核 3.审核不通过
                    newVo.setApplyId(applyId);
                    voList.add(newVo);
                } else {
                    newVo.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_PASS);// 审核状态 0.未审核 1.审核中 2.已审核 3.审核不通过
                    voList.add(newVo);
                }
            }
            this.prjPrdDtlGpsService.batchInsertWithDel(voList);
        } catch (BaseException e) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("新增GPS信息失败:" + e.getMessage());
            BaseLogUtils.newLogger("新增GPS信息失败").setKeys("tcDetailId" + tcDetailId).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
        } catch (Exception e)  {
            BaseLogUtils.newLogger("新增GPS信息失败").setKeys("tcDetailId" + tcDetailId).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("新增GPS信息失败:" + e.getMessage());
        }
        return result;
    }

	/**
	 * 导出车辆交接单
	 */
    @SuppressWarnings("resource")
	@RequestMapping(value = "/exportAssCarHvPdf.do", method = {RequestMethod.GET})
    public void exportAssCarHvPdf(HttpServletRequest request, HttpServletResponse response) {
        String tcDetailId = request.getParameter("tcDetailId");
        if (StringUtils.isEmpty(tcDetailId)) {
			return;
		}
        Map<String, Object> map = new HashMap<>();
        AssTrailCarHvVO vo1 = this.assTrailCarDService.selectTransferInfoById(Long.valueOf(tcDetailId));
        map.put("vo1", vo1);
        AssTrailCarHvQueryCondition qc = new AssTrailCarHvQueryCondition();
		qc.setDetailId(Long.valueOf(tcDetailId));
		List<AssTrailCarHvVO> vo2 = this.assTrailCarHvService.searchList(qc);
		if(vo2.size()>0){
			map.put("vo2", vo2.get(0));
		}else{
			map.put("vo2", vo2);
		} 

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        String filename = "车辆交接单导出";
        response.setCharacterEncoding("utf-8");
        OutputStream os = null;
        try {
            filename = new String(filename.getBytes("utf-8"), "ISO8859-1");
            response.setHeader("Content-disposition", "attachment; filename=" + filename + ".pdf");// 设定输出文件头
            response.setContentType("application/pdf");// 定义输出类型
            baos = new ExportAssUtils().exportAssCarHvPdf(map);
            os = response.getOutputStream();
            baos.writeTo(os);
            baos.flush();
            os.flush();
        } catch (UnsupportedEncodingException e) {
            BaseLogUtils.newLogger("导出车辆交接单").setKeys("tcId:" + tcDetailId).setThrowable(e).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
        } catch (IOException e) {
            BaseLogUtils.newLogger("导出车辆交接单").setKeys("tcId:" + tcDetailId).setThrowable(e).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
        } finally {
            //关闭流
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    BaseLogUtils.newLogger("IOException").setThrowable(e).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
                }
            }
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    BaseLogUtils.newLogger("IOException").setThrowable(e).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
                }
            }

        }
    }
    
    /**
     * 到新增/修改页面(拖车赎回-处置收款表)
     */
    @RequestMapping(value = "/toRecAmtPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toRecAmtPage(HttpServletRequest request, HttpServletResponse response) {
    	String dataId = request.getParameter("dataId");
    	String flag = request.getParameter("flag");//流程节点标识
    	String goFlag = request.getParameter("goFlag");//跳转标识
    	String assDealRecAmt_id = request.getParameter("assDealRecAmt_id");//主键
        ModelAndView view = new ModelAndView("ass/assTrailCarD/assRecAmtEdit");
        view.addObject("dataId", dataId);
        view.addObject("flag", flag);
        view.addObject("goFlag", goFlag);
        AssDealRecAmtVO recAmtVo = new AssDealRecAmtVO();
        if(StringUtils.isNotEmpty(assDealRecAmt_id)){
        	recAmtVo = this.assDealRecAmtService.selectById(Long.valueOf(assDealRecAmt_id));
        }
        view.addObject("recAmtVo", recAmtVo);//返回查询记录
        view.addObject("assDealRecAmt_id", assDealRecAmt_id);//数据主键
        List<SysDictionaryDTO> dataTypeCdList = sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd() ,InterfaceConstants.DATA_TYPE_CD);
        view.addObject("dataTypeCdList", dataTypeCdList);//数据类型

        return view;
    }
    
    /**
     * 删除(拖车赎回-处置收款表)
     */
    @RequestMapping(value = "/deleteRecAmt.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO deleteRecAmt(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            return result;
        }

        try {
            boolean success = this.assDealRecAmtService.removeById(Long.valueOf(id));
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
                BaseLogUtils.newLogger("删除处置收款表数据失败").setKeys("id:" + id).info();
            }
        } catch (BaseException ex) {
            BaseLogUtils.newLogger("删除处置收款表数据失败").setThrowable(ex).setKeys("id:" + id).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
        } catch (Exception ex) {
            BaseLogUtils.newLogger("删除处置收款表数据失败").setThrowable(ex).setKeys("id:" + id).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
        }
        return result;
    }
    /**
	 * 获取核销列表信息 kfc 170908
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/searchCapFundVerificationList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object searchCapFundVerificationList(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String redeem_Id = request.getParameter("redeem_Id");//赎回表ID
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(redeem_Id)){
			return result;
		}
		try {
			AssDealRedeemVO redeemVO = assDealRedeemService.selectById(Long.valueOf(redeem_Id));
			if(InterfaceConstants.REDEEM_TYPE_CD_1.equals(redeemVO.getRedeemTypeCd())){//赎回方式：赎回结清
				Long detailId = redeemVO.getDetailId();
				AssTrailCarDVO dVO = assTrailCarDService.selectById(detailId);
				AssTrailCarDInfQueryCondition con = new AssTrailCarDInfQueryCondition();
				con.setDetailId(detailId);
				List<AssTrailCarDInfVO>  dInfVO = assTrailCarDInfService.searchAssTrailCarDInfList(con);
				//获取数据
				if(CollectionUtils.isNotEmpty(dInfVO) && dInfVO.size() > 0){
					CapFundVfDtlQueryCondition capCon = new CapFundVfDtlQueryCondition();
					capCon.setPaySchId(dVO.getPaySchId());//支付表ID
					//capCon.setPaySchId(170815104004091L);//支付表ID
					//2018-1-11 10:11:17 jiangzg modify
					capCon.setVfTmMin(DateUtils.formatDateToString(dInfVO.get(0).getActBackDt(),"yyyy-MM-dd"));//最小核销时间（实际拖回日期）
					capCon.setVfTmMax(DateUtils.formatDateToString(new Date(),"yyyy-MM-dd"));//最大核销时间(当前日期)
					List<CapFundVfDtlDTO>  dtos = capFundVfDtlApiService.searchCapFundVerificationList(capCon);
					List<CapFundVfDtlDTO>  dtos2 = new ArrayList<CapFundVfDtlDTO>(); 
					for (CapFundVfDtlDTO capFundVfDtlDTO : dtos) {
						//vfTypCd(核销类型：1. 核销 2.冲红)   vfStsCd(核销状态集合：CAP0004：0.未分解1.分解中2.已分解3.已作废4.冲红中5.已冲红6.已转出)
						if (!capFundVfDtlDTO.getVfTypCd().equals("2") && !capFundVfDtlDTO.getVfStsCd().equals("5")) {
							dtos2.add(capFundVfDtlDTO);
						}
					}
					ListPageVO<CapFundVfDtlVO> listPage = new ListPageVO<CapFundVfDtlVO>(CapFundVfDtlVOTransform.toVOList(dtos2), CapFundVfDtlVOTransform.toVOList(dtos2).size());
					return listPage;
				}
			}
		}catch(BaseException ex) {
			BaseLogUtils.newLogger("获取核销列表信息失败").setThrowable(ex).setKeys("redeemId:" + redeem_Id).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
			throw ex;
		}catch(Exception ex) {
            BaseLogUtils.newLogger("获取核销列表信息失败").setThrowable(ex).setKeys("redeemId:" + redeem_Id).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		}
		return result;
	}
	
	 /**
     * 到申请冲红页面
     */
    @RequestMapping(value = "/toRevertFundPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toRevertFundPage(HttpServletRequest request, HttpServletResponse response) {
    	String vfIds = request.getParameter("vfIds");//CAP_FUND_VF_DTL表Id
    	String redeem_Id = request.getParameter("redeem_Id");//赎回表Id
    	String tcDetailId = request.getParameter("tcDetailId");//拖车明细表Id
    	String flag = request.getParameter("flag");//跳转标识
        ModelAndView view = new ModelAndView("ass/assTrailCarD/assRevertFundApplay");
        view.addObject("vfIds", vfIds);
        view.addObject("redeem_Id", redeem_Id);
        view.addObject("tcDetailId", tcDetailId);
        view.addObject("flag", flag);
        return view;
    }
	 /**
     * 冲红
     */
    @RequestMapping(value = "/revertFund.do", method = { RequestMethod.POST})
    @ResponseBody
    public DataResultVO revertFund(HttpServletRequest request, HttpServletResponse response) {
    	DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
    	String vfIds = request.getParameter("vfIds");//CAP_FUND_VF_DTL表Id
    	String redeem_Id = request.getParameter("redeem_Id");//赎回主表Id
    	String vfRem = request.getParameter("vfRem");//冲红原因
    	String tcDetailId = request.getParameter("tcDetailId");//拖车明细表Id
    	try { 
	    	AssTrailCarDVO vo = assTrailCarDService.selectById(Long.valueOf(tcDetailId));
	        AssTrailCarDInfVO infVo = this.assTrailCarDInfService.selectPNoPaySchNoByDataId(Long.valueOf(redeem_Id));
	        AssTrailCarDInfQueryCondition infCon = new AssTrailCarDInfQueryCondition();
	        infCon.setDetailId(Long.valueOf(tcDetailId));
		 	List<AssTrailCarDInfVO>  list = assTrailCarDInfService.searchAssTrailCarDInfList(infCon);
		 	Date actBackDt = list.get(0).getActBackDt();
	        //结清流程实例ID->结清流程编号->事业部编号->支付表ID->支付表编号->预冲红分解明细ID(批量)->冲红原因->冲红操作人ID->冲红操作人名称
	        CapFundVfDtlQueryCondition con = new CapFundVfDtlQueryCondition();
	        con.setProcessIntId(infVo.getpInstId());//结清流程实例ID
	        con.setProcessIntNo(infVo.getPNo());//结清流程编号
	        con.setBuOrgCd(vo.getBuOrgCd());//事业部编号
	        con.setDataId(Long.valueOf(redeem_Id));//赎回表主表ID
	        con.setPaySchNo(vo.getPaySchNo());//支付表编号
	        List<Long> ids = new ArrayList<Long>();
	        JSONArray vfIdsArray = JSONArray.fromObject(vfIds);
			for (Object object : vfIdsArray) {
				ids.add(Long.parseLong(object.toString()));
			}
	        //ids.add(Long.valueOf(vfId));
	        con.setIdList(ids);//冲红分解明细ID
	        con.setVfRem(vfRem);//冲红原因
	        con.setVfUsrId(CurrentThreadContext.getCurrentUserId());//冲红操作人Id
	        con.setVfUsrNm(CurrentThreadContext.getCurrentUserName());//冲红操作人名称
	        con.setActBackDt(actBackDt);//实际拖回日期
	        Boolean flag = capFundVfDtlApiService.revertFund(con);
        	 if (!flag) {
                 result.setSuccess(BaseConstant.IS_YESNO_NO);
                 result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL);
                 BaseLogUtils.newLogger("冲红失败").setKeys("vfIds:" + vfIds).info();
             }
		}catch (BaseException ex) {
            BaseLogUtils.newLogger("冲红失败").setThrowable(ex).setKeys("vfIds:" + vfIds).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
        } catch (Exception ex) {
            BaseLogUtils.newLogger("冲红失败").setThrowable(ex).setKeys("vfIds:" + vfIds).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
        }
        return result;
    }
    
    /**
     * 保存杂费附件备注
     * @param request
     * @param response
     * @return
     * @throws BaseException
     */
    @RequestMapping(value = "/modifyCostFileRem.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modifyCostFileRem(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String tcDetailId = request.getParameter("tcDetailId");
		String costFileRem = request.getParameter("costFileRem");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(tcDetailId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		AssTrailCarDVO entity = null;
		try {
			entity = new AssTrailCarDVO();
			entity.setId(Long.valueOf(tcDetailId));
			entity.setCostFileRem(costFileRem);
			//设置主表实体属性
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setMdfTm(new Date());
			boolean success = this.assTrailCarDService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.newLogger("保存杂费附件备注失败").setKeys("tcDetailId:" + tcDetailId, "DATA:" + JSONObject.toJSONString(entity)).info();
			}
		}catch (BaseException ex) {
            BaseLogUtils.newLogger("保存杂费附件备注失败").setThrowable(ex).setKeys("tcDetailId:" + tcDetailId, "DATA:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		}catch (Exception ex) {
            BaseLogUtils.newLogger("保存杂费附件备注失败").setThrowable(ex).setKeys("tcDetailId:" + tcDetailId, "DATA:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
		}
		return result;
	}
    /**
     * 初始化列表--变卖亏损信息
     * 
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/getAssDealSellLossList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getAssDealSellLossList(HttpServletRequest request, HttpServletResponse response) {
        AssDealSellLossQueryCondition qc = new AssDealSellLossQueryCondition();
        //设置查询条件
        String crtUsrId = request.getParameter("crtUsrId");//添加人
        String dataId = request.getParameter("dataId");//
        String taskNm = request.getParameter("taskNm");//添加节点
        if (StringUtils.isNotEmpty(crtUsrId)) {
            qc.setCrtUsrId(Long.valueOf(crtUsrId));
        }
        if (StringUtils.isNotEmpty(taskNm)) {
            qc.setTaskNm(taskNm);
        }
        qc.setIsDel(Long.valueOf(0));
        qc.setSellId(Long.valueOf(dataId));//变卖ID
        List<AssDealSellLossVO> list = this.assDealSellService.selectLossList(Long.valueOf(dataId));
        return list;
    }
    
    /**
     * 新增 /修改-- 变卖亏损信息
     */
    @RequestMapping(value = "/addAssDealSellLoss.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object addAssDealSellLoss(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        AssDealSellLossVO entity = new AssDealSellLossVO();
        // 处置id
        String dataId = request.getParameter("dataId");
        String lossCauseCdList = request.getParameter("lossCauseCdList");
        if (StringUtils.isEmpty(lossCauseCdList)) {
            throw new BaseException("无亏损原因，错误");
        }
        String taskNm = request.getParameter("taskNm");//变卖id
        String costRem = request.getParameter("costRem");//变卖id
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        if (StringUtils.isEmpty(dataId)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            return result;
        }
        if (StringUtils.isNotBlank(dataId)) {
            entity.setSellId(Long.valueOf(dataId));
        }
        entity.setCostRem(costRem);
        if (StringUtils.isNotEmpty(taskNm)) {
            entity.setTaskNm(taskNm);
        }
        try {
            List<AssDealSellLossVO> assDealSellLossVOS = assDealSellService.selectLossList(Long.valueOf(dataId));
            for (AssDealSellLossVO assDealSellLossVO : assDealSellLossVOS) {
                assDealSellLossVO.setIsDel(Long.valueOf(BaseConstant.IS_YESNO_YES));
                assDealSellService.modifyassDealSellLoss(assDealSellLossVO);
            }
            entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
            entity.setCrtTm(new Date());
            entity.setIsDel(Long.valueOf("0"));
            com.alibaba.fastjson.JSONArray array = JSON.parseArray(lossCauseCdList);
            for (Object lossCause : array) {
                entity.setLossCauseCd((String) lossCause);
                this.assDealSellService.addassDealSellLoss(entity);
            }
        } catch (BaseException ex) {
            BaseLogUtils.newLogger("新增(修改)亏损信息表数据失败").setThrowable(ex).setKeys("DATA:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
        } catch (Exception ex) {
            BaseLogUtils.newLogger("新增(修改)亏损信息表数据失败").setThrowable(ex).setKeys("DATA:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
        }
        return result;

    }
    /**
     * 新增 /修改-- 变卖亏损信息
     */
    @RequestMapping(value = "/addAssDealSellLossList.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object addAssDealSellLossList(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        AssDealSellLossVO entity = new AssDealSellLossVO();//获取参数
        String dataId = request.getParameter("dataId");//变卖id
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        if (StringUtils.isEmpty(dataId)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            return result;
        }
        if (StringUtils.isNotBlank(dataId)) {
            entity.setSellId(Long.valueOf(dataId));
        }
        String data = request.getParameter("parms[jsonStr]");
        String costRem = request.getParameter("costRem");
        String taskNm = request.getParameter("taskNm");
        com.alibaba.fastjson.JSONArray array = JSON.parseArray(data);
        for (Object lossCause : array) {
            String cause = (String) lossCause;
            entity.setCostRem(costRem);
            if (StringUtils.isNotEmpty(cause)) {
                entity.setLossCauseCd(cause);
            }
            if (StringUtils.isNotEmpty(taskNm)) {
                entity.setTaskNm(taskNm);
            }
            try {
                if (entity.getId() != null) {//修改
                    entity.setMdfTm(new Date());
                    entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
                    Long id = this.assDealSellService.modifyassDealSellLoss(entity);
                    result.setData(id);
                } else {//新增
                    entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
                    entity.setCrtTm(new Date());
                    entity.setIsDel(Long.valueOf("0"));
                    Long id = this.assDealSellService.addassDealSellLoss(entity);
                    result.setData(id);
                }
            } catch (BaseException ex) {
                BaseLogUtils.newLogger("新增(修改)亏损信息表数据失败").setThrowable(ex).setKeys("DATA:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
                throw ex;
            } catch (Exception ex) {
                BaseLogUtils.newLogger("新增(修改)亏损信息表数据失败").setThrowable(ex).setKeys("DATA:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
                throw ex;
            }
        }
        return result;

    }
    /**
     * 删除-- 变卖亏损信息
     */
    @RequestMapping(value = "/delAssDealSellLoss.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object delectAssDealSellLoss(HttpServletRequest request, HttpServletResponse response) throws BaseException {
       
	 	DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        AssDealSellLossVO entity = new AssDealSellLossVO();//获取参数
    	String data = request.getParameter("parms[jsonStr]");
    	//com.alibaba.fastjson.JSONArray array = JSON.parseArray("["+data+"]");
    	com.alibaba.fastjson.JSONArray array = JSON.parseArray(data);
    	for (Object object : array) {
    		JSONObject obj=	(JSONObject) object;
    		Long lossId=(Long) obj.get("id");//亏损id
    		String lossCauseCd=(String) obj.get("lossCauseCd");//亏损原因
		 	String costRem=(String) obj.get("costRem");//备注
		 	if(StringUtils.isNotBlank(costRem)){
				entity.setCostRem(costRem);
			}
		 	if(StringUtils.isNotBlank(lossCauseCd)){
				entity.setLossCauseCd(lossCauseCd);
			}
		 	if(null != lossId){
		 		entity.setId(lossId);
		 	}
			if(StringUtils.isEmpty(lossId)){
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
					return result;
			}
		
        try {
        	entity.setIsDel(Long.valueOf("1"));
            Long id = this.assDealSellService.modifyassDealSellLoss(entity);
            result.setData(id);
        } catch (BaseException ex) {
            BaseLogUtils.newLogger("删除亏损信息表数据失败").setThrowable(ex).setKeys("DATA:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
        } catch (Exception ex) {
            BaseLogUtils.newLogger("删除亏损信息表数据失败").setThrowable(ex).setKeys("DATA:" + JSONObject.toJSONString(entity)).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw ex;
        }
    	}
        return result;
    }
    
}

